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;
}