题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。要求一趟扫描完成。
题目来源:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
解题思路
- leetcode 链表题目中,链表结构体都是没有头结点的。每次我都会自动构造一个头结点。
- 链表题目其实都不难,画画图基本都能够解出来。
本题目使用双指针算法即可。
定义两个指针 first 和 second,首先令 first 指向第 n 个结点。然后初始化 second 指向头结点,而后 first 、second 指针依次向后移动,当 first 指向最后一个结点时,first 就指向倒数第 n + 1 个结点了。
实现代码
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode* phead = new ListNode(-1);
phead->next = head;
ListNode* first = phead,*second = phead;
while(n--)
{
first = first->next;
}
while(first->next)
{
first = first->next;
second = second->next;
}
second->next = second->next->next;
return phead->next;
}