Last active
December 18, 2017 07:40
-
-
Save rishi93/d445c8b060bb218893cb55539a33df0a to your computer and use it in GitHub Desktop.
Linked List (Java implementation)
This file contains hidden or 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 Node{ | |
| int data; | |
| Node next; | |
| Node(int data){ | |
| this.data = data; | |
| this.next = null; | |
| } | |
| } | |
| class LinkedList{ | |
| Node head; | |
| LinkedList(){ | |
| head = null; | |
| } | |
| /* Append a new node with data key to the linked list */ | |
| void add(int key){ | |
| if(head == null){ | |
| head = new Node(key); | |
| return; | |
| } | |
| Node curr = head; | |
| while(curr.next != null){ | |
| curr = curr.next; | |
| } | |
| curr.next = new Node(key); | |
| } | |
| /* Delete the first occurence of key */ | |
| void deleteKey(int key){ | |
| if(head.data == key){ | |
| head = head.next; | |
| return; | |
| } | |
| Node curr = head; | |
| /* Traverse until we encounter the previous node or the end of the list */ | |
| while(curr.next.data != key && curr != null){ | |
| curr = curr.next; | |
| } | |
| /* If the key doesn't exist in the list */ | |
| if(curr == null){ | |
| return; | |
| } | |
| curr.next = curr.next.next; | |
| } | |
| /* Delete the node at index position, index starts from 0 */ | |
| void deletePosition(int position){ | |
| if(position == 0){ | |
| head = head.next; | |
| return; | |
| } | |
| Node curr = head; | |
| for(int i = 0; i < position-1 && curr != null; i++){ | |
| curr = curr.next; | |
| } | |
| if(curr == null){ | |
| return; | |
| } | |
| curr.next = curr.next.next; | |
| } | |
| /* Function to traverse the linked list and print each node */ | |
| void printList(){ | |
| Node curr = head; | |
| while(curr != null){ | |
| System.out.print(curr.data + "->"); | |
| curr = curr.next; | |
| } | |
| System.out.print("null"); | |
| System.out.println(); | |
| } | |
| /* Calculating the size of the linked list */ | |
| int getSize(){ | |
| int count = 0; | |
| Node curr = head; | |
| while(curr != null){ | |
| curr = curr.next; | |
| count += 1; | |
| } | |
| return count; | |
| } | |
| } | |
| public class Test{ | |
| public static void main(String[] args){ | |
| LinkedList list = new LinkedList(); | |
| list.add(1); | |
| list.add(2); | |
| list.add(3); | |
| list.add(4); | |
| list.add(5); | |
| list.deleteKey(5); | |
| list.printList(); | |
| list.deletePosition(0); | |
| list.printList(); | |
| System.out.println("Length of the linked list is: " + list.getSize()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment