LeetCode18- 删除倒数第n个节点

image-20230318211344007

ans:

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
class Solution{

// 常用写法
public ListNode deleteNode(ListNode head ,int n){
if(head = null)return null;

// 定义虚拟头节点dw
ListNode dump = new ListNode();
dump.next = head;
ListNode cur = dump;
// 先找出长度
int length = getLength(head);
for(int i=1;i< length-n+1;i++){
cur =cur.next;
}

cur.next = cur.next.next;
return dump.next;
}


public int getLength(ListNode node){
int length =0;
while(node != null){
++length;
node = node.next;
}
return node;
}


public ListNode slowNode(ListNode head,int n){
if(head = null)return null;

// 定义虚拟头节点dw
ListNode dump = new ListNode();
dump.next = head;
ListNode cur = dump;
ListNode slow = cur;
ListNode fast =cur;
for(int i=0;i<=n ;i++){
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dump.next;

}



}



__END__