remove-nth-node-from-end-of-list

题目描述

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例

给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明

给定的 n 保证是有效的。

进阶

你能尝试使用一趟扫描实现吗?

解题思路

思路一

1.在头节点之前添加一个空节点a;
2.声明两个指针f和s指向空节点a,让head也指向a;
3.让s往后移动n位;
4.让f和s同时向后移动,直到s的next为空;
5.删除f后面的那个节点;
6.返回head->next。

思路二

1.遍历链表到末尾,得到链表长度l,让最后一个元素指向头节点,声明一个尾指针指向尾节点;
2.从尾节点开始向后移动l-n+1位,删除其后的节点,让尾节点指向空。

代码

思路一

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *first = new ListNode(-1);
        ListNode *second = first;
        first->next = head;
        head = first;
        int i = 0;
        while(i < n)
        {
            second = second->next;
            i++;
        }
        while(second->next)
        {
            first = first->next;
            second = second->next;
        }
        ListNode *temp = first->next;
        first->next = first->next->next;
        //free(temp);
        return head->next;
    }
};

相关文章:

  • 2021-12-26
  • 2021-11-26
  • 2021-09-07
  • 2021-10-27
  • 2021-11-14
  • 2021-08-17
猜你喜欢
  • 2021-10-20
  • 2021-07-10
  • 2021-10-19
相关资源
相似解决方案