原文:
Implement an algorithm to delete a node in the middle of a single 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
译文:
实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。
例子:
输入:指向链表a->b->c->d->e中结点c的指针
结果:不需要返回什么,得到一个新链表:a->b->d->e
思路:
把下一个节点的data值赋给当前节点的data,这样就使得当前节点和下一个节点看起来一样了。
然后把下一个节点删除,done!
这又是一道看过就知道,没看过就跪的题!回想去年时就被问道这道题,当时百思不得其解!没有头指针,只给指向自己的指针怎么能删除自己?!于是陷入万劫不复。。却不知道变一下思路。这种题面到有没准备到就亏大了!
package LinkLists;
import CtCILibrary.AssortedMethods;
import CtCILibrary.LinkedListNode;
public class S2_3 {
public static boolean deleteNode(LinkedListNode n) {
if(n==null || n.next==null) {
return false;
}
LinkedListNode next = n.next;
n.data = next.data; // 把下一个节点的值赋给当前节点
n.next = next.next; // 删除下一个节点
return true;
}
public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
deleteNode(head.next.next.next.next); // delete node 4
System.out.println(head.printForward());
}
}