forked from LeBW/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthFromEnd.java
More file actions
29 lines (29 loc) · 838 Bytes
/
RemoveNthFromEnd.java
File metadata and controls
29 lines (29 loc) · 838 Bytes
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
/**
* 19. Remove Nth Node From End of List
* <a href=https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/>
* Click here to see online description.
* </a>
*<br>
* Traverse the List in one pass.
* 双指针
* @author LBW
*/
public class RemoveNthFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode leader = head, cur = head;
for (int i = 0; i < n; i++)
leader = leader.next;
//if remove the first
if (leader == null) {
return head.next;
}
//go ahead, make cur.next be the node that is going to be deleted.
while (leader.next != null) {
leader = leader.next;
cur = cur.next;
}
//delete cur.next
cur.next = cur.next.next;
return head;
}
}