leetcode_Delete Node in a Linked List

来源:互联网 发布:ck one 知乎 编辑:程序博客网 时间:2024/06/08 03:36

描述:

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.

思路:

1.若不是最后一个,将当前节点的下一个节点的值赋值给当前节点,然后直接删除下一个节点即可。

2.若是最后一个,即currentNode.next==null,这就需要从头遍历一下当前链表了,找到倒数第二个节点,直接node.next=node.next.next;即可完成删除工作。

当然,本题目要求的仅仅是将当前节点删除即可。

代码:

public void deleteNode(ListNode node) {        if(node==null)            return;        node.val=node.next.val;        node.next=node.next.next;    }

0 0
原创粉丝点击