-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ19RemoveNthNodeFromEndofList.java
More file actions
55 lines (52 loc) · 1.24 KB
/
Q19RemoveNthNodeFromEndofList.java
File metadata and controls
55 lines (52 loc) · 1.24 KB
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
/**
* 19. Remove Nth Node From End of List
*
* @author ahscuml
* @date 2018/9/29
* @time 9:37
*/
public class Q19RemoveNthNodeFromEndofList {
/**
* 测试函数
*/
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
listNode1.next = listNode2;
listNode2.next = listNode3;
removeNthFromEnd(listNode1, 2);
while (listNode1 != null) {
System.out.print(listNode1.val);
listNode1 = listNode1.next;
}
}
/**
*
* */
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode start = dummy;
ListNode end = dummy;
for (int i = 0; i < n; i++) {
end = end.next;
}
while (end.next != null) {
end = end.next;
start = start.next;
}
start.next = start.next.next;
return dummy.next;
}
/**
* 链表的定义
*/
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}