LeetCode #237. Delete Node in a Linked List 删除链表中的节点

https://leetcode-cn.com/problems/delete-node-in-a-linked-list/

非常巧妙的一道题。

题目没有给head,心想没有head我怎么才能找到要删除的值对应的节点呢?

仔细一看,题中函数的参数给的不是值,而是要删除的节点node。反而降低了解题难度:

1. 把node.next的值赋给node

2. 把node.next指向node.next.next

其实相当于删除node.next

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public void deleteNode(ListNode node) {
11         node.val = node.next.val;
12         node.next = node.next.next;
13     }
14 }

猜你喜欢

转载自www.cnblogs.com/nemowang1996/p/10870993.html