【码图c语言】第五章 指针 基础实验3

建立单链表

通过课程进入题 号:586建立单链表语言要求:C++
建立带头结点的单链表,结点结构如下定义:
struct node
{
int data;
struct node *next;
};
struct node* createList(int data[],int n)函数实现建立单链表功能,具体说明如下:
输入参数:data是一个长度为n的数组,里面存储的建立单链表所需数据。
返回值:带头结点的单链表的首地址。
注意:单链表存储的数据和data里面数据顺序一致。
比如n=3,data存放的数据是1 2 3,则建立的单链表header所指的数据结点的数据依次为1,2,3。
如果出现错误,则输出"error",并返回NULL。
你可以用下面的这些函数测试createList得到的链表是否正确建立。


#include<stdio.h>
#include<stdlib.h>
struct node
{
	int data;
	struct node* next;
};
struct node* createList(int data[], int n);
void freelst(struct node* h);
void printlst(struct node* h);
int main()
{
	struct node* header = NULL, * p;
	int* data, n, i;
	scanf("%d", &n);
	data = (int*)malloc(n * sizeof(int));
	if (!data)return 0;
	for (i = 0; i < n; ++i)scanf("%d", data + i);
	header = (struct node*)createList(data, n);
	p = header;
	printlst(header);
	freelst(header);
	free(data);
	return 0;
}
void freelst(struct node* h)
{
	struct node* p = h->next;
	while (p)
	{
		h->next = p->next;
		free(p);
		p = h->next;
	}
	free(h);
}
void printlst(struct node* h)
{
	struct node* p = h->next;
	while (p)
	{
		printf("%d ", p->data);
		p = p->next;
	}
}

#include <stdio.h>
#include <stdlib.h>

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

struct node* createList(int data[], int n) {
    if (n < 0) {
        printf("error\n");
        return NULL;
    }

    // 创建头结点
    struct node *header = (struct node *)malloc(sizeof(struct node));
    if (!header) {
        printf("error\n");
        return NULL;
    }
    header->next = NULL;

    // 为数组中的每个元素创建一个链表节点并链接到链表中
    struct node *current = header;
    for (int i = 0; i < n; ++i) {
        struct node *new_node = (struct node *)malloc(sizeof(struct node));
        if (!new_node) {
            printf("error\n");
            // 如果分配内存失败,释放已创建的链表节点并返回NULL
            while (header) {
                struct node *temp = header->next;
                free(header);
                header = temp;
            }
            return NULL;
        }
        new_node->data = data[i];
        new_node->next = NULL;
        current->next = new_node;
        current = new_node;
    }

    return header;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值