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个结点,注意以下两个地方:
(1)要求只遍历一次,一个指针不行的情况下,要想到用两个指针;
(2)链表删除问题边界情况都有头结点的问题,所以要注意这里的边界情况(注释地方为第一次提交写错的地方)
C代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
struct ListNode *i=head, *j=head, *pi=head;
for(int k=1; k<n; k++)
j = j->next;
while(j->next != NULL)
{
pi = i;
i = i->next;
j = j->next;
}
if(i == head) // not if(pi == head)
{
head = head->next;
pi->next = NULL;
}
else
{
pi->next = i->next;
i->next = NULL;
}
return head;
}