forked from haobinaa/DataStructure-DesignPattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeleteLastNNode.java
55 lines (49 loc) · 1.33 KB
/
DeleteLastNNode.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
package com.haobin.offer;
/**
* @author: HaoBin
* @create: 2019/10/14 14:25
* @description: 删除倒数第N个节点
**/
public class DeleteLastNNode {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode tail = head;
for (int i = 2; i < 6; i++) {
ListNode node = new ListNode(i);
tail.next = node;
tail = node;
tail.next = null;
}
head = deleteLast(head, 2);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
static class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public static ListNode deleteLast(ListNode head, int n) {
if (head == null) {
return head;
}
ListNode pHead = head;
ListNode first = head;
ListNode second = head;
// 保持n个间隔
for (int i = 0; i <= n; i++) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
// 第一个指针指向尾部,则第二个指针指向待删除节点的前一个节点
second.next = second.next.next;
return pHead;
}
}