#174 Remove Nth Node From End of List

来源:互联网 发布:fdd lte网络 编辑:程序博客网 时间:2024/06/12 01:44

题目描述:

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

 Notice

The minimum number of nodes in list is n.

Example

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

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

Challenge 

Can you do it without getting the length of the linked list?

题目思路:

这题只要找到需要删除的node的前一个node的位置,就很容易办了。怎么找这个位置呢?我先用一个fast pointer,让它从dummy head开始先走n步;然后用一个slow pointer从dummy head开始跟它一起走,等fast走到最后一个node的时候,slow指向的位置就是我们想找的位置了。

Mycode (AC = 56ms):

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @param n: An integer.     * @return: The head of linked list.     */    ListNode *removeNthFromEnd(ListNode *head, int n) {        // write your code here        ListNode *dummy = new ListNode(0);        dummy->next = head;                // let fast ptr go n steps first        ListNode *slow = dummy, *fast = dummy;        int k = 0;        while (k < n) {            fast = fast->next;            k++;        }                // find the ptr where ptr->next is the         // element we want to delete        while (fast->next) {            slow = slow->next;            fast = fast->next;        }                // delete the element        slow->next = slow->next->next;        return dummy->next;    }};


0 0
原创粉丝点击