leetcode - 19. Remove Nth Node From End of List

双指针问题,自己在head前面加一个头结点,边界处理会变得很简单
在这里插入图片描述

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode a(1);
        a.next=head;
        ListNode* p1=&a;
        ListNode* p2=&a;
        for(int i=0;i<n;++i)
        {
            p2=p2->next;
        }
        while(p2->next!=NULL)
        {
            p2=p2->next;
            p1=p1->next;
        }
        p2=p1->next;
        p1->next=p2->next;
        return a.next;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/88853613