leetcode-19-java

问题:19. Remove Nth Node From End of List

1
2
3
4
5
6
7
Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

leetcode地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public  ListNode removeNthFromEnd(ListNode head, int n) {
//创建起始
ListNode start = new ListNode(0);
start.next = head;

//创建游标
ListNode cursor1 = start;
ListNode cursor2 = start;
while (n > 0) {
cursor1 = cursor1.next;
n --;
}


while (cursor1.next != null) {
cursor1 = cursor1.next;
cursor2 = cursor2.next;
}

cursor2.next = cursor2.next.next;
return start.next;
}