19. Remove Nth Node From End of List

来源:互联网 发布:东方财富软件使用方法 编辑:程序博客网 时间:2024/05/30 23:03

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.

分析:加入两个指针,fast和slow;
其中fast走到第n个节点时,slow开始走,这个时候slow和fast相距n;
然后当fast走到尾节点时,slow的下一个节点就是要删除的节点;
接下来做删除操作即可。

/** * 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 NULL;        ListNode *temp=new ListNode(-1);        temp->next=head;        ListNode* fast=temp,*slow=temp;        for(int i=0;i<n;i++)            fast=fast->next;                while(fast->next)        {            slow=slow->next;            fast=fast->next;        }        ListNode* delete_node=slow->next;        slow->next=slow->next->next;        delete delete_node;        return temp->next;    }};
原创粉丝点击