LeetCode 19. Remove Nth Node From End of List

来源:互联网 发布:淘宝资产拍卖 编辑:程序博客网 时间:2024/04/30 11:37

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;}


0 0
原创粉丝点击