You are given a Doubly linked list and an integer K . Your task is to insert the integer K at the head of the given linked list.
Input
The first line contains an integer N and K.
The next line contains N integers, the elements of the Doubly linked list.
Constraints:
1 <= N <= 1000
1 <=K, value<= 1000
Output
Print the updated Doubly linked list in new line.
Example
Input:
5 2 1 2 3 4 5
Output:
2 1 2 3 4 5
Solution:–
import java.util.*; import java.lang.*; import java.io.*; class Node{ Node prev; int data; Node next; Node(int x) { prev=null; data=x; next=null; } } public class Main { static Node head=null; static void insertion(int x) { Node newNode=new Node(x); if(head==null) { head=newNode; return ; } Node temp=head; while(temp.next!=null) { temp=temp.next; } newNode.prev=temp; temp.next=newNode; } static void addHead(int x) { Node newNode = new Node(x); newNode.next=head; head.prev=newNode; head=newNode; } static void printList() { if(head==null) { return; } Node temp=head; while(temp!=null) { System.out.print(temp.data+" "); temp=temp.next; } } public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); for(int i=0;i<n;i++) { int value=sc.nextInt(); insertion(value); } addHead(k); printList(); } }
Add a Comment