建立单链表
通过课程进入 | 题 号: | 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;
}