题目描述:
解析:
?设置两个指针,一个先走n步,然后两个指针一起走,当第二个指针走到最后的时候,第一个指针正好走到倒数第n+1个
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
int i = 0;
ListNode l1 = head;
ListNode l2 = dummy;
while(i < n) {
l1 = l1.next;
i++;
}
while(l1 != null) {
l1 = l1.next;
l2 = l2.next;
}
l2.next = l2.next.next;
ListNode ans = dummy.next;
return ans;
}
}
?
|