Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Created June 23, 2014 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UncleGarden/f19d7c4a4a7666ef5144 to your computer and use it in GitHub Desktop.
Save UncleGarden/f19d7c4a4a7666ef5144 to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 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());
}
}
}
@chrislukkk
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment