Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save WOLOHAHA/3bdeb536e126c10f4159 to your computer and use it in GitHub Desktop.

Select an option

Save WOLOHAHA/3bdeb536e126c10f4159 to your computer and use it in GitHub Desktop.
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
/**
* 2.3 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 is returned, but the new linked list looks like a- >b- >d->e
*
*
* @Runtime & spaces
* runtime: O(1)
* space: O(1)
*/
public boolean delNode(ListNode p){
if(p==null||p.next==null)
return false;
ListNode next=p.next;
p.val=next.val;
p.next=next.next;
return true;
}
//Note that this problem cannot be solved if the node to be deleted is the last node in
//the linked list.That's ok—your interviewer wants you to point that out,and to discuss
//how to handle this case.You could,for example,consider marking the node as dummy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment