forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
44 lines (39 loc) · 974 Bytes
/
Solution.java
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
/**
* @author Anonymous
* @since 2019/11/20
*/
public class Solution {
class ListNode {
int val;
ListNode next;
}
/**
* 删除链表的节点
*
* @param head 链表头节点
* @param tobeDelete 要删除的节点
*/
public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
if (head == null || tobeDelete == null) {
return head;
}
// 删除的不是尾节点
if (tobeDelete.next != null) {
tobeDelete.val = tobeDelete.next.val;
tobeDelete.next = tobeDelete.next.next;
}
// 链表中仅有一个节点
else if (head == tobeDelete) {
head = null;
}
// 删除的是尾节点
else {
ListNode ptr = head;
while (ptr.next != tobeDelete) {
ptr = ptr.next;
}
ptr.next = null;
}
return head;
}
}