19. Remove Nth Node From End of List C++

使用双指针法,可以仅遍历一次完成节点的定位

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* l = new ListNode(0);
        l = head;
        ListNode* r = new ListNode(0);
        r = l;
        while(n--)
            r = r->next;
        //用于判断head是否为单节点链表
        if(r == NULL)
            return head->next;
        while(r != NULL && r->next != NULL)
        {
            r = r->next;
            l = l->next;
        }
        ListNode* temp = new ListNode(0);
        temp = l->next;
        l->next = l->next->next;
        if(temp)
            delete(temp);
        return head;
    }
};

猜你喜欢

转载自www.cnblogs.com/tornado549/p/10029385.html