3

LeetCode-237-删除链表中的节点

 2 years ago
source link: https://segmentfault.com/a/1190000040666171
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-237-删除链表中的节点

删除链表中的节点

题目描述:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:脑筋急转弯

第一时间没反应过来,为什么没有给head节点???想了会才想明白为什么要强调参数为非末尾的节点,解决方法就是将要删的节点的值和next都改成要删节点的next节点的值和next。

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

    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        head.next = new ListNode(5);
        ListNode node_1 = new ListNode(1);
        head.next.next = node_1;
        head.next.next.next = new ListNode(9);

        System.out.println("before deleteNode");
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
        deleteNode(node_1);
        System.out.println("after deleteNode");
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }
}

【每日寄语】 世上只有一种英雄主义,就是在认清生活真相之后依然热爱生活。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK