-
Notifications
You must be signed in to change notification settings - Fork 6
/
DeleteNodeInLinkedList.java
74 lines (69 loc) · 1.6 KB
/
DeleteNodeInLinkedList.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package io.ziheng.codinginterviews;
/**
* 单链表节点
*/
class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 剑指 Offer 面试题 18:删除链表节点
*
* 题目描述:
* 给定单向链表头节点指针与目标节点指针,
* 请以 O(1) 时间复杂度从单向链表中删除该目标节点。
*
* 知识点:["链表"]
*/
public class DeleteNodeInLinkedList {
/**
* 主函数 -> 测试用例
*
* @param args
* @return void
*/
public static void main(String[] args) {
// ...
}
/**
* 剑指 Offer 面试题 18:删除链表节点
*
* @param head
* @param node
* @return void
*/
public void deleteNode(ListNode head, ListNode node) {
// 异常情况
if (head == null || node == null) {
return;
}
// 尾节点
if (node.next == null) {
ListNode currentNode = head;
while (currentNode.next != node) {
currentNode = currentNode.next;
}
currentNode.next = null;
freeNode(node);
// 非尾节点
} else {
ListNode delNode = node.next;
node.val = delNode.val;
node.next = delNode.next;
freeNode(delNode);
}
}
private void freeNode(ListNode node) {
node.val = 0;
node.next = null;
}
}
/* EOF */