Created
December 14, 2018 00:22
-
-
Save overcyn/a5648da5cd40f606d4baf385fdf2a945 to your computer and use it in GitHub Desktop.
Linked List
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
| public class Node { | |
| Node next; | |
| object val; | |
| public Node(object val) { | |
| this.val = val | |
| } | |
| } | |
| public class LinkedList { | |
| Node head; | |
| public void AddNode(object newVal) { | |
| if (head == null) | |
| { | |
| head = new Node(newVal); | |
| } | |
| else | |
| { | |
| Node currentNode = head; | |
| while(currentNode.next != null) | |
| { | |
| currentNode = currentNode.next; | |
| } | |
| currentNode.next = new Node(newVal); | |
| } | |
| } | |
| public Object GetObject(int index) { | |
| if (head == null) | |
| { | |
| return null | |
| } | |
| else | |
| { | |
| Node currentNode = head; | |
| for (int x = 0; x < index; x++) | |
| { | |
| if (currentNode.next) | |
| { | |
| currentNode = currentNode.next | |
| } | |
| else { | |
| return null | |
| } | |
| } | |
| return currentNode.val | |
| } | |
| } | |
| public void DeleteNode(int index) { | |
| if (head == null) | |
| { | |
| return null; | |
| } | |
| else if (index == 0) | |
| { | |
| head = head.next | |
| } | |
| else | |
| { | |
| Node currentNode = head; | |
| for (int x = 0; x < index + 1; x++) | |
| { | |
| if (currentNode.next) | |
| { | |
| if (x + 1 == index) | |
| { | |
| if (!currentNode.next.next) | |
| { | |
| currentNode.next = null | |
| } | |
| else | |
| { | |
| currentNode.next = currentNode.next.next | |
| } | |
| } | |
| else | |
| { | |
| currentNode = currentNode.next | |
| } | |
| } | |
| else { | |
| return null | |
| } | |
| } | |
| } | |
| } | |
| public void DeleteNode(int index) { | |
| if (head == null) | |
| { | |
| return null; | |
| } | |
| else if (index == 0) | |
| { | |
| head = head.next | |
| } | |
| Node currentNode = head; | |
| for (int x = 0; x < index - 1; x++) | |
| { | |
| if (currentNode.next) | |
| { | |
| currentNode = currentNode.next | |
| } | |
| else | |
| { | |
| return null | |
| } | |
| } | |
| currentNode.next = currentNode.next.next | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment