[leetcode] 19. Remove Nth Node From End of List

来源:互联网 发布:python sql注入脚本 编辑:程序博客网 时间:2024/06/03 07:14

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

For 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.
Try to do this in one pass.

这道题是删除链表倒数第N个节点,题目难度为Easy。


题目的关键是如何找倒数第N个节点,有经验的同学可能很容易想到用双指针法,让fast指针先走N个节点,然后同时移动快慢指针,当fast指针到达链表尾部时slow指针指向的节点即是倒数第N个节点。另外需要注意的是,如果倒数第N个节点是头节点需要特殊处理,具体代码:

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode* fast = head;        ListNode* slow = head;        ListNode* prev = NULL;        int cnt = 0;                while(fast && cnt<n) {            fast = fast->next;            cnt++;        }        while(fast) {            fast = fast->next;            prev = slow;            slow = slow->next;        }                if(prev) {            prev->next = slow->next;            return head;        }        else {            return slow->next;        }    }};

0 0