这道题让我们移除链表倒数第N个节点,限定n一定是有效的,即n不会大于链表中的元素总数。还有题目要求我们一次遍历解决问题,那么就得想些比较巧妙的方法了。比如我们首先要考虑的时,如何找到倒数第N个节点,由于只允许一次遍历,所以我们不能用一次完整的遍历来统计链表中元素的个数,而是遍历到对应位置就应该移除了。
那么我们需要用两个指针来帮助我们解题,pre和cur指针。首先cur指针先向前走N步,如果此时cur指向空,说明N为链表的长度,则需要移除的为首元素,那么此时我们返回head->next即可。
如果cur存在,则一直走到链表末尾null,此时pre指针也跟着走,因为pre跟cur一直相差n,所以最后pre就是要去掉的节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur = head;
ListNode pre = head;
int count = 1;
if(head.next==null) return head.next;
while(cur.next!=null){
cur = cur.next;
count++;
if(count==n){
if(cur.next==null){
return head.next;//要删除的刚好是head
}
}
if(count>n+1){
pre = pre.next;
}
}
ListNode tmp = pre.next;
pre.next = tmp.next;
return head;
}
}