Created
December 6, 2020 03:48
-
-
Save shahzadaazam/2df2a29958b2e75d0172257a3c6d772b to your computer and use it in GitHub Desktop.
LinkedList custom implementation with append, prepend and delete operations
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
class Main { | |
public static void main(String[] args) { | |
Node head = new Node(5); | |
LinkedList linkedList = new LinkedList(head); | |
linkedList.append(6); | |
linkedList.append(7); | |
linkedList.prepend(4); | |
linkedList.deleteWithValue(7); | |
linkedList.printList(); | |
} | |
} | |
class Node { | |
int value; | |
Node next; | |
public Node(int value, Node next) { | |
this.value = value; | |
this.next = next; | |
} | |
public Node(int value) { | |
this.value = value; | |
} | |
} | |
class LinkedList { | |
Node head; | |
public LinkedList() { | |
} | |
public LinkedList(Node head) { | |
this.head = head; | |
} | |
public void append(int value) { | |
if (head == null) { | |
head = new Node(value); | |
return; | |
} | |
Node current = head; | |
while (current.next != null) { | |
current = current.next; | |
} | |
current.next = new Node(value); | |
} | |
public void prepend(int value) { | |
Node newHead = new Node(value); | |
newHead.next = head; | |
head = newHead; | |
} | |
public void deleteWithValue(int value) { | |
if (head == null) return; | |
if (head.value == value) { | |
head = head.next; | |
return; | |
} | |
Node current = head; | |
while (current.next != null) { | |
if (current.next.value == value) { | |
current.next = current.next.next; | |
return; | |
} | |
current = current.next; | |
} | |
} | |
public void printList() { | |
Node current = head; | |
while (current != null) { | |
System.out.print( current.value + ", "); | |
current = current.next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment