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

LeetCode 19. Remove Nth Node From End of List

2016-03-10 01:18 465 查看
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)单链表同样不带头结点;(2)如果删除的是头结点,注意这种情况单独讨论;(3)算法思想就是设置两个指针,第一个指针走n步时,第二个指针才刚刚开始走。这样第一个指针到达终点时,第二个指针恰好在倒第N个;删除指针还是用了pre,其实可以p->val=p->next->val;但是这里还是有p->next是否为NULL的问题,要记得判断,我就采用pre直接删除了。

二、C语言实现

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *p,*q,*pre;
p=head;
while(n--){
p=p->next;
}
if(p==NULL){//表示要删除第一个结点
return head->next;
}
pre=head;
q=head->next;
while(p->next!=NULL){
p=p->next;
pre=q;
q=q->next;
}
pre->next=q->next;
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息