LeetCode 19. Remove Nth Node From End of List(链表)

来源:互联网 发布:autodesk 设计造型软件 编辑:程序博客网 时间:2024/05/03 19:30

LeetCode 19. Remove Nth Node From End of List(链表)

  • LeetCode 19 Remove Nth Node From End of List链表
    • 问题描述
    • 解题思路
    • 参考代码

  • By Scarb
  • Scarb’s Blog

Tags:
- Linked List
- Two Pointers

问题描述

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个数字并且返回这个链表。
解题思路是使用两个指针,第一个指针遍历链表,第二个指针在第一个指针的前n-1个位置,当第一个指针遍历到链表结尾,第二个指针所在的位置就是第n-1个结点,此时可以删除第n个结点。
需要使用一个虚拟结点,放在链表的开头来处理边界情况。

参考代码

#include <iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x): val(x), next(NULL) {}};class Solution{public:    ListNode* removeNthFromEnd(ListNode *head, int n)    {        ListNode *dummy = new ListNode(0);        dummy->next = head;        ListNode *p1 = dummy;        ListNode *p2 = dummy;        for (int i = 0; i < n + 1; ++i)        {            p1 = p1->next;        }        while (p1 != NULL)        {            p1 = p1->next;            p2 = p2->next;        }        //cout << p2->val << endl;        p2->next = p2->next->next;        return dummy->next;    }};int main(){    ListNode *l1 = new ListNode(1);    ListNode *l2 = new ListNode(2);    ListNode *l3 = new ListNode(3);    ListNode *l4 = new ListNode(4);    ListNode *l5 = new ListNode(5);    l1->next = l2;    l2->next = l3;    l3->next = l4;    l4->next = l5;    Solution sl = Solution();    ListNode *temp = sl.removeNthFromEnd(l1, 2);    while (temp != NULL)    {        cout << temp->val << " ";        temp = temp->next;    }    system("pause");    return 0;}