如何创建有N个节点的单链表

来源:百度知道 编辑:UC知道 时间:2024/06/09 06:04:01
最好能提供算法思想和算法设计!
谢谢!!!

开辟一个空间,赋上一个值,连到前面节点,就形成链表喽
code如下:
#include "stdio.h"
#include"malloc.h"

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

link *creat(int n) //创建链表
{
link *head,*p,*s;
int i;
if(n<1) return NULL;
p=head=(link *)malloc(sizeof(link));
for(i=1;i<=n;i++)
{
s=(link *)malloc(sizeof(link));
scanf("%d",&s->data);
p->next=s;
p=s;
}
p->next=NULL;
return head;
}

void display(link *head)//显示链表内容
{
link *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}

void main()
{
link *head;
head=creat(5);//创建一个5个节点的链表
printf("链表:\n");
display(head);
}