题目

remove-nth-node-from-end-of-list


算法

直接模拟

  • 两个指针
  • 第一个先走n步
  • 然后两个一起走,第一个到达尾部,
  • 第二个是导数第n个节点

代码


struct ListNode{
    int val;
    ListNode * next;
    ListNode(int x):val(x),next(NULL) {}
};


class Solution{
public:
    ListNode* removeNthFromEnd(ListNode* head,int n){
        if(!head->next)  return NULL;
        ListNode * pre=head,*cur=head;
        for(int i=0;i<n;++i)
            cur=cur->next;
        if(!cur) return head->next;
        while(cur->next){
            cur=cur->next;
            pre=pre->next;
        }
        pre->next=pre->next->next;
        return head;
    }
};

results matching ""

    No results matching ""