19. Remove Nth Node From End of List

来源:互联网 发布:linux进程消失查日志 编辑:程序博客网 时间:2024/06/04 01:20

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个节点,通过两个指针,可以巧妙地在一次遍历中完成删除操作,具体思路如图:
这里写图片描述
在处理两个指针的时候要小心边界情况,图中加了一个Dummy节点,处理起来更方便。

/** * 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 dummyNode = ListNode(0);        ListNode* dummy = &dummyNode;        //把DummyNode放在链表开头        dummy->next = head;        ListNode* first = dummy;        ListNode* second = dummy;        for (int i = 0; i < n + 1; i++) {            second = second->next;        }        while (second) {            first = first->next;            second = second->next;        }        first->next = first->next->next;        //这里注意要返回head,不是dummy        return dummy->next;    }};
原创粉丝点击