7-4 求链式线性表的倒数第K项(20 分)

7-4 求链式线性表的倒数第K项(20 分)

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

输入格式:

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

输出格式:

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

输入样例:

4 1 2 3 4 5 6 7 8 9 0 -1

输出样例:

7

开始看到链式线性表,就觉得也许会输入特别特别特别多的数,怕数组承受不住,就用链表存,创建链表添加结点时候可以用头插法,求倒数第k项就变成了从头到尾遍历链表找第k项。
后来又用数组,不过也是开了一个很大的数组,看到也可以过~

链表代码

#include<stdio.h>
#include<stdlib.h>
struct node{
    int date;
    struct node* next;
}; 
int main()
{
    struct node* list=(struct node*)malloc(sizeof(struct node));
    list->date=0x7fffffff;     //写的是带头结点的链表
    list->next=NULL;
    long long k;
    scanf("%lld",&k);
    int date;
    while(scanf("%d",&date)!=EOF&&date>=0)
    { 
        struct node* newnode=(struct node*)malloc(sizeof(struct node));
        newnode->date=date;
        newnode->next=NULL;
        newnode->next=list->next;
        list->next=newnode;
    }
    long long count=1;
    struct node* p=list->next;
    while(p!=NULL)
    {
        if(count==k)
         break;

        count++;
        p=p->next;
    } 
    if(p!=NULL)
     printf("%d",p->date);
    else
     printf("NULL");
}

数组代码

#include<stdio.h>
#include<string.h>
#define maxn 0x7fffffff
int a[maxn];
int main()
{
    int k;
    scanf("%d",&k);
    int count=0,x;
    while(1)
    {
        scanf("%d",&x);
        if(x<0)break;
        else 
        {
            a[count]=x;
            count++; 
        } 
    }
    if(count-k<0)
     printf("NULL\n");
    else
     printf("%d\n",a[count-k]); 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值