forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
40 lines (31 loc) · 977 Bytes
/
Solution2.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
// 19. Remove Nth Node From End of List
// https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
//
// 使用双指针, 对链表只遍历了一遍
// 时间复杂度: O(n)
// 空间复杂度: O(1)
public class Solution2 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode p = dummyHead;
ListNode q = dummyHead;
for( int i = 0 ; i < n + 1 ; i ++ ){
assert q != null;
q = q.next;
}
while(q != null){
p = p.next;
q = q.next;
}
p.next = p.next.next;
return dummyHead.next;
}
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};
ListNode head = new ListNode(arr);
System.out.println(head);
head = (new Solution2()).removeNthFromEnd(head, 2);
System.out.println(head);
}
}