[LeetCode 解題報告]019.Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

內容:刪除倒數第k個節點 

考察點:快慢指針,ListNode *cur=head, *pre=head, cur先走k步,走完需要注意此時cur有可能指向NULL,刪除的節點即爲head,然後cur與pre一起走到單鏈表尾部,此時pre指向待刪除節點前一個節點。

/**
 * 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* cur = head;
        ListNode* pre = head;
        
        for (int i = 0; i < n; i ++)
            cur = cur->next;
        if (cur == NULL)
            return head->next;
        while (cur->next) {
            pre = pre->next;
            cur = cur->next;
        }
        pre->next = pre->next->next;
        return head;
    }
};

完, 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章