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);
        }
    }
  • 相关阅读:
    程序员第一定律:关于技能与收入
    JS注册/移除事件处理程序
    关于程序猿,你不知道的15件事
    .NET后台输出js脚本的方法
    新项目经理必读:分析什么是项目经理
    项目如何开始:怎样和客户一起搞定需求
    【转】为什么程序员讨厌修改静态检查问题
    js的with语句使用方法
    软件版本号 详解
    PHP记忆碎片2投票汇总
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6675892.html
Copyright © 2011-2022 走看看