Add a node at the beginning
The new node is always added at the beginning node of the given Linked List. For example if the given Linked List is 50->100->105->220->250 and we add an item 330 at the beginning, then the Linked List becomes 330->50->100->105->220->250
If you are not getting how it has done then please just see the previous post of this topic...
The new node is always added at the beginning node of the given Linked List. For example if the given Linked List is 50->100->105->220->250 and we add an item 330 at the beginning, then the Linked List becomes 330->50->100->105->220->250
package com.dashzin.linklist;
public class AddFirst {
Node head;
static class Node{
int data;
Node next;
Node(int data){
this.data=data;
next=null;
}
}
/* This method will prints data of linked
list starting from head */
public void printList(){
while(head!=null){
System.out.print(head.data+" ");
head=head.next;
}
}
/* Inserts a new Node at front of the list.
*/
public void insert(int new_data){
Node new_node=new Node(new_data); // Allocate the Node & Put the data
new_node.next=head; //Make next of new Node as head
head=new_node; // Move the head to point to new Node
}
public static void main(String args[]){
// creating four node for linklist
AddFirst lkl=new AddFirst();
lkl.head=new Node(1);
Node first=new Node(2);
Node sec=new Node(3);
Node third=new Node(4);
//Link all the node with each other.....
lkl.head.next=first;
first.next=sec;
sec.next=third;
// calling insert method to insert node at
beginning position..
lkl.insert(5);
//calling method to print_list.....
lkl.printList();
}
}
If you are not getting how it has done then please just see the previous post of this topic...
0 comments:
Post a Comment