给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
分析:删除链表中倒数第K个节点的问题在于找到倒数第k个节点; 方法:设置两个指针front, behind,front从head开始向前走k步后,behind从head开始与front一起向前移动,当front到达尾节点的时候,behind与front相隔K,此时behind指向的就是倒数第k个节点。 边界1:k等于链表长度时候,front移动到了尾节点,直接返回head->next;
/**
* 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)
{
if (!head) return head;
ListNode * front = head;
ListNode * behind = head;
while(n--) // n有效的前提下
{
front = front->next;
}
if (front == nullptr)
{
head = head->next;
return head;
}
while(front->next != nullptr)
{
front = front->next;
behind = behind->next;
}
behind->next = behind->next->next;
return head;
}
欢迎交流,批评指正!