public class linkedlistDemo {
Node head = null;
public void insertAtFirst(int data) {
Node node = new Node(data);
if(null == head) {
head = node;
}
else {
node.next = head;
head = node;
}
}
public void insertAtLast(int data) {
Node temp = head;
if(null == head) {
temp = new Node(data);
}
Node current = temp;
while(current.next != null) {
current= current.next;
}
Node node = new Node(data);
node.next = current.next;
current.next = node;
}
public void insertAtSpecPos(int data,int pos) {
Node temp = new Node(data);
temp.next = head;
Node current = head;
for(int i =0;i<pos;++i){
}
Node node = new Node(data);
node.next = current.next;
current.next = node;
}
public void print() {
Node temp = head;
while(temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
linkedlistDemo l = new linkedlistDemo();
l.insertAtFirst(3);
l.insertAtFirst(2);
l.insertAtFirst(1);
System.out.println("insert At First");
l.print();
System.out.println("===========");
l.insertAtLast(4);
System.out.println("insert At last");
l.print();
System.out.println("===========");
l.insertAtSpecPos(5, 3);
System.out.println("insert At spec");
l.print();
System.out.println("===========");
}
}
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
Comments
Post a Comment