Last active
August 29, 2015 14:02
-
-
Save chrislukkk/37c7a2b140795abff900 to your computer and use it in GitHub Desktop.
CareerCup_2.3 - NodeDeletion
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
package Chapter2; | |
//Singly Linked List | |
public class MyLinkedList<T> { | |
public Node<T> head; | |
public MyLinkedList(Node<T> h) { | |
head = h; | |
} | |
public MyLinkedList(T[] dataArray) { | |
if (dataArray == null || dataArray.length <= 0) | |
return; | |
head = new Node<>(dataArray[0], null); | |
Node<T> node = head; | |
for (int i = 1; i < dataArray.length; i++) { | |
node.next = new Node<T>(dataArray[i], null); | |
node = node.next; | |
} | |
} | |
public void print() { | |
Node<T> cur = head; | |
while (cur != null) { | |
System.out.print(cur.data); | |
if (cur.next != null) { | |
System.out.print(" -> "); | |
} | |
cur = cur.next; | |
} | |
System.out.println(); | |
} | |
} |
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
package Chapter2; | |
public class Node<T> { | |
public T data; | |
public Node<T> next; | |
public Node(T d, Node<T> n){ | |
data = d; | |
next = n; | |
} | |
} |
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
package Chapter2; | |
public class NodeDeletion { | |
public static <T> void deleteNode(Node<T> node) { | |
if (node == null) | |
return; | |
Node<T> next = node.next; | |
if (next != null) { | |
node.data = next.data; | |
node.next = next.next; | |
next = null; | |
} else { | |
throw new UnsupportedOperationException("Grrrr..can not delete last node:("); | |
} | |
} | |
public static void main(String[] args) { | |
MyLinkedList<String> list = new MyLinkedList<>(new String[] { "a", "b", | |
"c", "d", "e" }); | |
list.print(); | |
Node<String> nodeC = list.head.next.next; | |
deleteNode(nodeC); | |
list.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment