Created
June 23, 2014 14:52
-
-
Save UncleGarden/f19d7c4a4a7666ef5144 to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* Implement an algorithm to delete a node in the middle of a singly linked | |
* list, given only access to that node. EXAMPLE Input: the node c from the | |
* linked list a->b->c->d->e Result: nothing isreturned, but the new linked list | |
* looks like a- >b- >d->e | |
* | |
* @author Jiateng | |
*/ | |
public class CC2_3 { | |
public static LinkedList deleteNode(LinkedList list, int k) { | |
if (list == null || list.size() < k || k <= 0) { | |
return null; | |
} | |
int i = 0; | |
LinkedList newList = new LinkedList(); | |
for (int j = 0; j < list.size(); j++) { | |
i++; | |
//remove one, the range will be 1 - size() | |
if (i != k && i < list.size()) { | |
newList.add(list.get(i)); | |
} | |
} | |
return newList; | |
} | |
public static void main(String[] args) { | |
LinkedList list = new LinkedList(); | |
int k = 10; | |
for (int i = 0; i < 10; i++) { | |
list.add(i); | |
} | |
//LinkedList newList = deleteNode(list, 0); | |
LinkedList newList = deleteNode(list, 5); | |
//LinkedList newList = deleteNode(list, k); | |
if (newList != null) { | |
System.out.println(newList.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think according to the problem definition, you will not have access to all the nodes before the deleted node in list, in other words the procedure signature will only be public static LinkedList deleteNode(Node deletedNode)