码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-27 11:47:08      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Remove Nth Node From End of List

 Total Accepted: 54129 Total Submissions: 197759My Submissions

 

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()
{

}

  

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

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4532619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!