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.
题目解析:
(1)保持两个指针,让他们相差n就可以了
(2)主要是边界问题
1、{1},1的情况下,处理的时候,我们当
k>=0
的时候也就是要删除第一个元素,比较特殊,因此得特别对待。
#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 *p = head;
int k = n-1;
while(p->next!=NULL && k>=0)
{
p = p->next;
k--;
}
if(k>=0)
{
head = head->next;
return head;
}
ListNode *q = head;
while(p->next!=NULL)
{
p = p->next;
q = q->next;
}
q->next = q->next->next;
return head;
}
int main(void)
{
ListNode *head;
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->val = 1;
node->next = NULL;
head = node;
removeNthFromEnd(head, 1);
system("pause");
return 0;
}