您的位置:首页 > Web前端 > Node.js

Remove Nth Node From End of List —— Leetcode

2015-03-31 10:51 232 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: