[LeetCode] Remove Nth Node From End of List

来源:互联网 发布:知乎和百度有什么区别 编辑:程序博客网 时间:2024/06/03 20:06

Remove Nth Node From End of List

写完最长前缀,看了一眼下一个easy,发现是个几行代码的题。so,写了吧。
题目:

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.

  • 解法:先用一个指针p指向头节点,然后把头节点head移动n次,然后再两个指针一起移动直到head移动到结尾,最后删除p的next就是倒数第n个节点了(p到head的距离为n).
/** * 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* pkResult = new ListNode(0);        pkResult->next = head;//新建一个节点并把next指向head,方便后面返回.        ListNode* p = pkResult;        for (; n--; head = head->next);//把head节点移动n次.        for (; head; head = head->next, p = p->next);//没移动到尾,就继续往下移动,但这些p也要跟着移动.        p->next = p->next->next;//把p的next删除.        return pkResult->next;    }};

欢迎访问我的github,leetcode持续更新: https://github.com/tsfissure/LeetCode

1 0
原创粉丝点击