【链表尾插法】求链表中第n个数据的值

题目描述

根据输入数据创建链表,并输出指定位置的数据

如果输入位置不存在,则输出“位置有误”

注意:要求用尾插法,头插法创建之后求的结果是肯定是错误的

输入

第一行输入一个整数n
第二行输入n个整数
第三行输入一个整数p

输出

第p个数据的值

#include "stdio.h"
#include "stdlib.h"

struct node{
    int data;
    struct node *next;
};

void destroylink(struct node *h);   
struct node * createlink(int n);
struct node * findbypos(struct node *h,int pos);

main()
{
    struct node *p,*head=NULL;
    int n,d;
    scanf("%d",&n);
    head = createlink(n);
    scanf("%d",&d);
    p = findbypos(head,d);
    //输出结果
    if (p == NULL) {
        printf("位置有误");
    } else {
        printf("%d", p->data);
    }

    destroylink(head);  
}

struct node * createlink(int n) {
    struct node *head = NULL;
    struct node *tail = NULL;
    int data;
    for (int i = 0; i < n; i++) {
        scanf("%d", &data);
        struct node *newNode = (struct node *)malloc(sizeof(struct node));
        newNode->data = data;
        newNode->next = NULL;
        if (head == NULL) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }
    return head;
}

struct node * findbypos(struct node *h,int pos) {
    struct node *current = h;
    int count = 1;
    while (current!= NULL) {
        if (count == pos) {
            return current;
        }
        current = current->next;
        count++;
    }
    return NULL;
}

void destroylink(struct node *h)
{
    struct node *q;
    while(h!=NULL)
    {
        q=h;
        h=h->next;
        free(q);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值