[leetcode]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.

双指针扫描。

当N等于3的时候,起初如下,


然后int i=1;i<N;i++直到如下


然后判断当前节点是不是最后一个,如果是最后一个,则是删除第一个节点,直接返回start->next就可以,如果不是那么start与end同时往后移动,


直到end->next是最后一个节点,此时start->next就是要删除的节点。

代码如下:


// test19RemoveNthNodeFromEndofList.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"


/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}

};


int isEnd(ListNode *theNode);
ListNode *removeNthFromEnd(ListNode *head, int n);


int _tmain(int argc, _TCHAR* argv[])
{
//ListNode *r1;
//ListNode *r2;
//ListNode *r3;
//ListNode *r4;
//ListNode *r5;
//ListNode *head;
//r1 =  new ListNode(0);
//r2 = new ListNode(0);
//r3 = new ListNode(0);
//r4 = new ListNode(0);
//r5 = new ListNode(0);
//r1->val = 1;
//r1->next = r2;


//r2->val = 2;
//r2->next = r3;


//r3->val = 3;
//r3->next = r4;
//r4->val = 4;
//r4->next = r5;
//r5->val =5;
//r5->next = NULL;
ListNode *r1;
ListNode *r2;
ListNode *r3;
r1 = new ListNode(0);
r2 = new ListNode(0);
r3 = new ListNode(0);
r1->next = r2;
r1->val = 1;
r2->next = r3;
r2->val = 2;
r3->next = NULL;
r3->val = 3;


ListNode *res = removeNthFromEnd(r1, 2);
return 0;
}


ListNode *removeNthFromEnd(ListNode *head, int n) 
{
if (n <= 0)
return head;
ListNode *start = head;
ListNode *end = head;
ListNode *temp;
for (int i = 1; i < n; i++)
{
end = end->next;
}
if (isEnd(end))
return start->next;
else
{
while (!isEnd(end->next))
{
end = end->next;
start = start->next;
}
temp = start->next->next;
start->next = temp;


}
return head;
}
int isEnd(ListNode *theNode)
{
if (theNode->next == NULL)
return 1;
return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值