Skip to content

Instantly share code, notes, and snippets.

@unnisworld
Created November 9, 2018 07:45
Show Gist options
  • Save unnisworld/16992018b10c19c07f6538376839100b to your computer and use it in GitHub Desktop.
Save unnisworld/16992018b10c19c07f6538376839100b to your computer and use it in GitHub Desktop.
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