LeetCode问题解答:19. Remove Nth Node From End of List

来源:互联网 发布:js push json 编辑:程序博客网 时间:2024/05/29 13:43

难度:Medium

源链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

描述:

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

Note:
Given n will always be valid.
Try to do this in one pass.


思考与解答:

该题需要在一个单向链表上移除倒数第N个节点,同时对效率做出了要求,需要一趟完成,也就是不要把整个链表扫一遍知道节点数量后

再从头去数到第N个节点。

对于这道题,需要3个指针来进行,首先用两个指针确定一个区间,大小为n,我们让这个区间在整个链表上移动,最终区间尾到底时,头

部正好就落在倒数第N位,同时为了链接去掉一个节点的链表,需要多余的一个指针来记住倒数第N个节点的前一个节点的地址。

要注意的是,需要对倒数第N个节点的前一个节点进行分类,因为它可能根本不存在。

具体代码:

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode* lastn = NULL;        ListNode* nth = head;        ListNode* p = head;        for (int i = 0; i < n-1; i++) {            p = p->next;        }        while (p->next != NULL){            lastn = nth;            p = p->next;            nth = nth->next;        }        if (lastn != NULL) {            lastn->next = nth->next;            return head;        } else {            return nth->next;        }            }};


原创粉丝点击