LeetCode 19. Remove Nth Node From End of List

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.
解析:
给定一个链表和一个int类型数值n,删除链表中从末尾起的第n个节点,并返回头节点指针。要求依次遍历解决问题。考虑设置双指针slow和fast,fast先跑n步,然后两个指针一块往后遍历,则当fast指向末尾时,slow指针正好为倒数第n个元素。实际处理中当fast->next指向末尾时,此时slow->next正好指向倒数第n个元素。此时show充当了前驱元素的作用,通过执行slow->next = slow->next->next来删除元素。同时要考虑头指针为空的情况以及n等于链表长度的情况,即删除第一个节点。具体代码参考下面。
[cc lang=”C++”]
/**
* 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 == NULL || head -> next == NULL)
return NULL;
ListNode *slow = head;
ListNode *fast = head;
for(int index = 0; index < n; index ++) { fast = fast->next;
}
if(!fast)//判断fast是否存在,比如n长度等于链表长度的情况,即删除第一个节点
{
return head->next;
}
while(fast->next)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};
[/cc]

One Comment

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据