-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode_0015.java
106 lines (86 loc) · 2.27 KB
/
LeetCode_0015.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.lijieyao.rabbitmq.hello;
import java.util.HashMap;
import java.util.Map;
/**
* 力扣第15题
*/
public class LeetCode_0015 {
public static void main(String[] args) {
// ListNode a5 = new ListNode(5);
// ListNode a4 = new ListNode(4,a5);
// ListNode a3 = new ListNode(3,a4);
ListNode a2 = new ListNode(2);
ListNode a1 = new ListNode(1,a2);
ListNode head = removeNthFromEnd(a1, 2);
ListNode curr = head;
while (true) {
System.out.println(curr.val);
curr = curr.next;
if (curr == null) {
return;
}
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
if (head.next == null) {
return null;
}
// 序号,当前节点
Map<Integer, ListNode> map = new HashMap<>();
int curr = 0;
ListNode current = head;
while (true) {
map.put(curr, current);
if (current.next == null){
break;
}
current = current.next;
curr++;
}
if (map.size() < n) {
return null;
}
int index = map.size() - n;
int preIndex = map.size() - n - 1;
if (index == 0){
return head.next;
}
// 前一个节点
ListNode pre = map.get(preIndex);
// 当前节点
ListNode cur = map.get(index);
// 节点置换
pre.next = cur.next;
return head;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 大佬优化方案
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
int traverse = traverse(head, n);
if (traverse == n)
return head.next;
return head;
}
private int traverse(ListNode node, int n) {
if (node == null)
return 0;
int num = traverse(node.next, n);
if (num == n)
node.next = node.next.next;
return num + 1;
}
}