剑指 Offer 18. 删除链表的节点

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动

示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.

示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
 
说明:
题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

思路

使用两个变量记录上一个节点和当前节点,如果相等,则pre.next = crrent.next

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public static void main(String[] args) {

ListNode head = new ListNode(8);
ListNode myhead = head;
for (int i = 0; i < 10; i++) {
ListNode listNode = new ListNode((int) (Math.random() * 100));
myhead.next = listNode;
myhead = listNode;
}
myhead.next = new ListNode(9);
System.out.println(head);

Solution solution = new Solution();
ListNode listNode = solution.deleteNode(head, 9);
System.out.println(listNode);

}

private static class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val){
return head.next;
}
ListNode pre = head , current = head.next;

while (current != null){
if (current.val == val){
pre.next = current.next;
return head;
}
pre = current;
current = current.next;
}
return head;
}
}