zoukankan      html  css  js  c++  java
  • Programming Ability Test学习 3-05. 求链式线性表的倒数第K项(15)

    3-05. 求链式线性表的倒数第K项(15)

    时间限制
    250 ms
    内存限制
    65536 kB
    代码长度限制
    8000 B
    判题程序
    Standard

    给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。

    输入格式说明:

    输入首先给出一个正整数K,随后是若干正整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。

    输出格式说明:

    输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息“NULL”。

    样例输入与输出:

    序号 输入 输出
    1
    4 1 2 3 4 5 6 7 8 9 0 -1
    
    7
    
    2
    6 3 6 7 8 2 -2
    
    NULL
    

    提交代码

    注:创建一个只有头结点的链表;head->Next=NULL;然后使用头插法,负数就不输入,遍历的时候直接从头结点开始,取第N个数即可。如果N>head->length,输出“NULL”。

    #include<stdio.h>
    #include<stdlib.h>
    #include <malloc.h>
    typedef struct Node
    {
       int dex;
       int length;
       struct Node * Next;
    }node,*Link;
    
    //创建空链表 
    node * create(node *head)
    {
        head=(node *)malloc(sizeof(node));
        head->Next=NULL;
        return head;
    }
    //头插法 
    void insert(node *head)
    {
        struct Node *tail;
        tail=head;
        head->length=0;
        int dex;
        while(scanf("%d",&dex))
        {
            if(dex<0)break;
            tail=(node *)malloc(sizeof(node));
            tail->dex=dex;
            tail->Next=head->Next;
            head->Next=tail;
            head->length++;
        }
    }
    //找第N个数 
    void find(node *head,int N)
    {
        if(N>head->length)printf("NULL
    ");
        else{
        int i=1;
        node* pthis;
        pthis=head->Next;
        while(pthis!=NULL)
        {
            if(i==N){printf("%d
    ",pthis->dex);break;}
            i++;
            pthis=pthis->Next;
        } 
        }
    } 
    //删除链表 
    void delLink(node *head)
    {
        struct Node *pthis;
        pthis=head;
        while(pthis!=NULL)
        {
            free(pthis);
            head=head->Next;
            pthis=head;
        } 
    }
    
    int main()
    {
        int N;
        scanf("%d",&N);
        
        struct Node *head;
        head=create(head);
        insert(head);
        find(head,N);
        delLink(head);
        return 0;
    } 
    View Code
  • 相关阅读:
    Jmeter 调试接口用例怎么判断提取的上一个接口返回值是正确的?
    Jmeter 加密处理方法
    Apache Ignite 学习
    jmeter 中 浮点数计算精度问题
    httprunner 使用总结
    oh-my-zsh 安装及使用
    内置装饰器二:@property
    内置装饰器一:@classmethod、@staticmathod
    python实现列表的排序
    Mac git简易使用
  • 原文地址:https://www.cnblogs.com/a842297171/p/4749769.html
Copyright © 2011-2022 走看看