Leetcode 237. Delete Node in a Linked List

来源:互联网 发布:今天美国非农数据 编辑:程序博客网 时间:2024/06/05 20:54

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.

本题只给出需要删除的节点,前置节点,链表头节点都没有给出,所以无法直接删除。只能从删除结点开始,将后面节点的值依次向前挪。

我的解法:

遇到问题:while的终止条件需提前一个节点,否则无法删除最后一个节点。之前写的while(after != null)

public class Solution {    public void deleteNode(ListNode node) {        ListNode now = node;        ListNode after = node.next;                while(after.next != null){            now.val = after.val;            now = now.next;            after = after.next;        }                now.val = after.val;        now.next = null;            }}



discuss里的简单解法:

问题:没有判定条件,循环不会一直执行吗?

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


0 0
原创粉丝点击