Delete Node in a Linked List 删除链表中的某个节点

来源:互联网 发布:ipad手写板软件 编辑:程序博客网 时间:2024/03/29 23:20

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.


有时候,人会有点定式思维了,想着,要是没有前一个节点,怎么可能把当前节点删除掉呢?

这个问题的巧妙之处就是没有前一个节点也是可以的。

比如例子中,我们要删3这个节点,我们可以通过把 3 节点的值变成4,然后把后面的4这个节点删除点。


运行时间:


代码是有史以来最简短的了。

public class DeleteNodeinaLinkedList {    public void deleteNode(ListNode node) {        node.val = node.next.val;        node.next = node.next.next;    }}



1 0
原创粉丝点击