Created
November 9, 2018 07:45
-
-
Save unnisworld/16992018b10c19c07f6538376839100b 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 { | |
private Node head; | |
public static void main(String[] args) { | |
LinkedList ll = new LinkedList(); | |
ll.add(1); | |
ll.add(2); | |
ll.add(3); | |
ll.add(4); | |
ll.print(); | |
ll.delete(1); | |
ll.print(); | |
ll.delete(3); | |
ll.print(); | |
// ll.delete(4); | |
// ll.print(); | |
} | |
public void add(int data) { | |
if (head == null) { | |
head= new Node(data, null); | |
return; | |
} | |
// Go to the end of the list. | |
Node currentLastNode = head; | |
while (currentLastNode.next != null) { | |
currentLastNode = currentLastNode.next; | |
} | |
Node newLastNode = new Node(data, null); | |
currentLastNode.next = newLastNode; | |
} | |
public boolean delete(int dataToDelete) { | |
Node currentNode = head; | |
Node previousNode = null; | |
while(currentNode != null) { | |
if (currentNode.data == dataToDelete){ | |
if (previousNode != null) { | |
previousNode.next = currentNode.next; | |
} | |
else { | |
// delete first node | |
head = currentNode.next; | |
} | |
return true; | |
} | |
else { | |
previousNode = currentNode; | |
currentNode = currentNode.next; | |
} | |
} | |
return false; | |
} | |
public void print() { | |
Node tmp = head; | |
while(tmp != null) { | |
System.out.print(tmp.data + "->"); | |
tmp = tmp.next; | |
} | |
System.out.println(); | |
} | |
class Node { | |
public int data; | |
public Node next; | |
Node(int data, Node next) { | |
this.data = data; | |
this.next = next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment