您的位置:首页 > Web前端 > Node.js

leetcode_19题——Remove Nth Node From End of List(链表)

2015-05-27 09:57 393 查看

Remove Nth Node From End of List

Total Accepted: 54129 Total Submissions: 197759My Submissions
Question Solution

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.

Hide Tags

Linked List Two Pointers

Have you met this question in a real interview?
Yes

No

Discuss

这道题题目要求删除链表中指定的倒数第n个结点,并且采用一次遍历,所以应该采用两个指针的方法

先将指针ptr1和ptr2之间的距离弄成n,再往后同时后移,而由于涉及到结点的删除,还要弄一个指针指到ptr1的前面那个结点处就可以了,

这道题要考虑到结点删除时是尾结点还是头结点还是中间结点

#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *ptr1,*ptr2,*ptr0;
ptr0=head;
ptr1=head;
ptr2=head;
int N=n-1;
while(N--)
ptr2=ptr2->next;

if(ptr2->next==NULL)
if(ptr1->next!=NULL)
return ptr1->next;
else
return NULL;
ptr1=ptr1->next;
ptr2=ptr2->next;
while(ptr2->next!=NULL)
{ptr2=ptr2->next;ptr1=ptr1->next;ptr0=ptr0->next;}
if(n==0)
{ptr1->next=NULL;return head;}
ptr0->next=ptr1->next;
return head;
}
int main()
{

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐