zoukankan      html  css  js  c++  java
  • [LeetCode]Remove Nth Node From End of List

    题目:Remove Nth Node From End of List

    删除链表从尾部到头部第N的节点。

    思路:

    两个指针,一个从头开始前移N个节点后,第二个指针开始移动,当第一指针移动到末尾时,第二个指针指向的是从尾部到头部的第N个节点。

    注意:

    1.N不合法,大于链表长度

    2.要删除的是头结点

    /*****************************************************************************************
    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.
    *****************************************************************************************/
    #include<stdio.h>
    
    struct ListNode {
        int val;
        struct ListNode *next;
    };
    
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
            if(n <= 0)return head;
            struct ListNode *p = head;
        for(;n > 0 && p!= NULL;n--)p = p->next;
        
        if(n > 0)return head;//n过大,比链表的实际长度大
        if(p == NULL){//要删除的是头结点
            p = head;
            head = head->next;
            free(p);
            return head;
        }
    
        struct ListNode *f = head;//第二个指针
        while(p->next != NULL){//两个指针一起移动
            p = p->next;
            f = f->next;
        }
        p = f->next;
        f->next = p->next;
        free(p);
        return head;
    }
    
    void main(){
        int k = 5;
        struct ListNode *l = (struct ListNode *)malloc(sizeof(struct ListNode));
        l->val = k;
        l->next = NULL;
        while(k--){
            struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
            p->val = k;
            p->next = l;
            l = p;
        }
    
        struct ListNode *r = l;
        while(r != NULL){
            printf("%d ",r->val);
            r = r->next;
        }
        printf("
    ");
    
        r = removeNthFromEnd(l,3);
        
        while(r != NULL){
            printf("%d ",r->val);
            l = r;
            r = r->next;
            free(l);
        }
    }
  • 相关阅读:
    使用B或BL跳转时,下一条指令的地址的计算
    【flask-Email】邮件发送
    【MAC】 命令行解压缩 rar 文件
    【flask_sqlalchemy】模糊查询
    【python】集合 list差集|并集|交集
    【pycharm】Mac版快捷键
    【mysql】查询最新的10条记录
    【Python】—— 获取当前运行函数名称和类方法名称
    【Python】—— 获取函数内部变量名称
    【python3】 抓取异常信息try/except
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6675892.html
Copyright © 2011-2022 走看看