1.题目
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
给出链表1->2->3->4->5->null和 n = 2.删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
2.思路
这道题的关键就在于如何找到倒数第n个节点的前一个节点!创建两个指针放在头指针处,第一个指针fast下移n-1次后开始判断链表是否只有n个节点;如果有n个以上节点,第二个节点slow开始与fast平行下移,当fast到达最后时 slow刚好到达倒数第n个的前一个,这时开始删除。
3.代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
if(head==NULL)
{return NULL;}
int i;
ListNode *fast=head;
ListNode *slow=head;
ListNode *rear=new ListNode(0);
rear->next=head;
for(i=0;i<n;i++)
{
fast=fast->next;
}
if(fast==NULL)
{
head=head->next;
return head;
}
while(fast->next!=NULL)
{ fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return rear->next;
}
};
4.感想
这时是做了好几道题后觉得最有意思的一道题啦!!!挺好玩的,很像两个人速度相同的人一前一后跑步,做了这道题后,一去操场跑步还会想起链表移动的场景,是不是有点走火入魔了……