【算法设计与分析作业题】第十周:19. Remove Nth Node From End of List

题目

C++ solution

/**
 * 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* p = new ListNode(0);
        p->next = head;
        ListNode* first = p;
        ListNode* second = p;
        for (int i = 0; i < n + 1; ++i)
        {
            first = first->next;
        }
        while (first != NULL) {
            first = first->next;
            second = second->next;
        }
        second->next = second->next->next;

        return p->next;
    }
};

简要题解

  1. 新建一个节点 p 指向 head,处理特殊情况(如删除 head 节点的情况)
  2. 新建 first 和 second 两个指针指向 p,先单独移动 first 指针使两个指针的距离为 n+1,然后同步移动这两个指针,当 first 指针移动到 list 尾部时(等于 NULL),second 指针指向倒数第 n+1 个 Node,使用 second->next = second->next->next 即可移除倒数第 n 个 Node。

猜你喜欢

转载自blog.csdn.net/For_course/article/details/83962824
今日推荐