现在的位置: 首页 > 综合 > 正文

Remove Nth Node From End of List — leetcode

2019年04月22日 ⁄ 综合 ⁄ 共 572字 ⁄ 字号 评论关闭

几个测试用例:

1. n > len

2. n = len ,删除首部

/**
 * 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) {
        if(head==NULL || n<1)
            return head;
        
        ListNode addHead(-1);
        addHead.next = head;
        ListNode *fast = &addHead;
        ListNode *slow = &addHead;
        
        for(int i = 0; (i < n)&&fast; i++)//此处用n,让fast slow保持n个间隔,slow->next 为所需删除的元素
            fast = fast->next;
            
        if(fast == NULL)// n > len
            return head;
            
        while(fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode *tmp = slow->next;
        slow->next = slow->next->next;
        delete tmp;
        return addHead.next;
    }    
};

抱歉!评论已关闭.