Leetcode19.删除链表的倒数第N个节点(C语言)

 暴力解法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* p=head;
    int num=1;
    //统计链表总长度
    while(p->next!=NULL)
    {
        p=p->next;
        num++;
    }
    //倒数第n个即正数第num-n+1个
    p=head;
    //需要使p到待删除节点的前一个,即到第num-n个 又p当前已在第一个 所以循环num-n-1次
    //但若num-n-1<=0,即要删除的是第一个
    if (n==num)return head->next;
    for(int i=1;i<num-n;i++)
    {
        p=p->next;
    }
    struct ListNode*q=p->next;
    p->next=p->next->next;
    free(q);
    q=NULL;
    p=NULL;
    return head;
}

法2:快慢指针法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


/* Description:
 * 使用快慢指针的方法, 快指针比慢指针先跑n个节点,
 *等快指针到头的时候,慢指针所指向的就是待删除的节点。
 */
typedef struct ListNode Node;

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    Node *fast = head;
    Node *slow = head;
    Node *last_slow = NULL;
    int i=0;
    
    /* fast pointer runs n steps first */
    while(fast){
        if(i==n){
            break;
        }
        fast = fast->next;
        i++;
    }
    
    /* fast and slow run together till fast be NULL,
     * at this point, slow pointer got the right node to be deleted.
     * last_slow pointer to get last pointer to slow.
     */
    while(fast){
        fast = fast->next;
        
        last_slow = slow;
        slow = slow->next;
    }
    
    if(last_slow){
        last_slow->next = slow->next;
        free(slow);/* free mem of node to be deleted */
    }else{/* if last_slow is NULL, head will be deleted. */
        head = head->next;
        free(slow);
    }
    return head;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值