Created
July 23, 2017 13:54
-
-
Save visparashar/48cacb192ba97dd13e5f206623b1f609 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LinkedList{ | |
Node head; | |
Node current; | |
public static class Node{ | |
int data; | |
Node next; | |
Node(int d){ | |
data =d; next=null; | |
} | |
} | |
// insert at the fr=ont of the linkedlist | |
public void insertAtFirst(int d){ | |
if(head ==null) | |
{ | |
head = new Node(d); | |
// return true; | |
} | |
else{ | |
Node n = new Node(d); | |
n.next =head; | |
head =n; | |
} | |
// return false; | |
} | |
public void insertAfter(int n1,int d){ | |
Node temp =head; | |
while(temp!=null){ | |
if(temp.data==n1){ | |
Node n =new Node(d); | |
n.next =temp.next; | |
temp.next =n; | |
break; | |
}else{ | |
temp=temp.next; | |
} | |
} | |
} | |
public void insert(int d){ | |
if(head==null) | |
{ | |
System.out.println("out"); | |
head =new Node(d); | |
current =head; | |
// return true; | |
}else{ | |
System.out.println("in "); | |
Node n = new Node(d); | |
current.next=n; | |
current=current.next; | |
// return true; | |
} | |
} | |
public void delete(int d){ | |
Node currentNode=head; | |
Node previousNode=null; | |
if(head.data ==d){ | |
head = head.next; | |
}else{ | |
while(currentNode!=null){ | |
if(currentNode.data==d){ | |
previousNode.next=currentNode.next; | |
break; | |
}else{ | |
previousNode=currentNode; | |
currentNode =currentNode.next; | |
} | |
} | |
} | |
} | |
public void show(){ | |
System.out.println("---Showing---"); | |
Node myNode =head; | |
while(myNode!=null){ | |
System.out.println(myNode.data); | |
myNode =myNode.next; | |
} | |
} | |
// delete linkedlist at a given position | |
public void deleteAtPosition(int d){ | |
Node temp =head; | |
Node prev =null; | |
int count=1; | |
if(d==1){ | |
head =head.next; | |
}else{ | |
while(temp!=null) | |
{ | |
if(count==d){ | |
prev.next=temp.next; | |
break; | |
}else{ | |
prev =temp; | |
temp =temp.next; | |
count++; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment