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

19. Remove Nth Node From End of List(Linked List)

2016-05-26 15:51 633 查看

Title

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.

Language C

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(head == NULL){
return NULL;
}
int i;
struct ListNode *p, *q, *r;
p = head;
q->next = head;
r = q; //r=q not r=head or r->next=head;
for(i = n; i > 0; i--, p = p->next);
while(p != NULL){
p = p->next;
q = q->next;
}
q->next = q->next->next;
return r->next;
}


runtime:4ms

思路

双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点。

牛人博客 Thx.

对指针的理解,需要再加强下,指针——C的灵魂
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表