-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeleteNodeInLinkedList.java
More file actions
67 lines (45 loc) · 1.39 KB
/
DeleteNodeInLinkedList.java
File metadata and controls
67 lines (45 loc) · 1.39 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
package swordPointOffer;
/**
* @Author: Wenhang Chen
* @Description:给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 返回删除后的链表的头节点。
* <p>
* 注意:此题对比原题有改动
* <p>
* 示例 1:
* <p>
* 输入: head = [4,5,1,9], val = 5
* 输出: [4,1,9]
* 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
* 示例 2:
* <p>
* 输入: head = [4,5,1,9], val = 1
* 输出: [4,5,9]
* 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
*
* <p>
* 说明:
* <p>
* 题目保证链表中节点的值互不相同
* 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
* @Date: Created in 8:46 3/30/2020
* @Modified by:
*/
public class DeleteNodeInLinkedList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val) return head.next;
ListNode pre = head, cur = head.next;
while (cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
if (cur != null) pre.next = cur.next;
return head;
}
}