c语言创建链表的函数 c语言创建链表每一步详解

c语言创建链表?#includestdio.h
#includestdlib.h
typedef struct data { int number; struct data *next; } DATA;
int main() { int n; DATA *head,*p;
printf("how many?\n"); scanf("%d",n); head=create(n); printf("there is all\n");
while ( head!=NULL ) { printf("%d ",head-number); head=head-next; } printf("\n");
while ( head!=NULL ) { p=head; head=head-next; free(p); }
return 0;
}
DATA *create(int n) { DATA *head=NULL,*t=NULL,*tial=NULL; int i;
printf("let's create it\n"); head=(DATA*)malloc(sizeof(DATA));
if ( !head ) { printf("error"); return NULL; }
head-next=NULL; printf("enter your data\n");scanf("%d",head-number);
for ( i=1,tial=head;in;i++ ) {
t=(DATA*)malloc(sizeof(DATA)); if ( !t ) { printf("error"); return head; }
scanf("%d",t-number); t-next=NULL; tial-next=t; tial=t;
}
return head;
}
C语言如何创建单链表?C语言创建单链表如下:
#include"stdio.h"
#include"stdlib.h"
#include"malloc.h"
#include "iostream.h"
typedef struct node
{
intdata;
node * next;
}node , * List;
void create(int n)
{
int c;
List s,L;
L=(List)malloc(sizeof(node));
L-next=NULL;
printf("请输入第1个数据:");
scanf("%d",c);
L-data=https://www.04ip.com/post/c;
for(int i=2;i=n;i++)
{
s=(List)malloc(sizeof(node));
printf("请输入第%d个数据:",i);
scanf("%d",c);
s-data=https://www.04ip.com/post/c;
s-next=L;
L-next =s;
}
printf("链表创建成功!");
}
void main()
{
int n;
printf("请你输入链表的个数:");
scanf("%d",n);
create(n);
}
单链表创建方法:
单链表的建立有头插法、尾插法两种方法 。
1. 头插法
单链表是用户不断申请 存储单元和改变链接关系而得到的一种特殊 数据结构,将链表的左边称为链头,右边称为链尾 。头插法建单链表是将链表右端看成固定的,链表不断向左延伸而得到的 。头插法最先得到的是尾结点 。
由于链表的长度是随机的,故用一个while循环来控制链表中结点个数 。假设每个结点的值都大于O,则循环条件为输入的值大于o 。申请 存储空间可使用malloc()函数实现 , 需设立一申请单元 指针,但malloc()函数得到的指针并不是指向 结构体的指针 , 需使用 强制类型转换,将其转换成结构体型指针 。刚开始时,链表还没建立,是一空链表,head 指针为NULL 。
链表建立的过程是申请空间、得到数据、建立链接的循环处理过程 。
2. 尾插法
若将链表的左端固定,链表不断向右延伸,这种建立链表的方法称为尾插法 。尾插法建立链表时,头 指针固定不动,故必须设立一个搜索指针 , 向链表右边延伸 , 则整个算法中应设立三个链表指针,即头指针head、搜索指针p2、申请单元指针pl 。尾插法最先得到的是 头结点 。
C语言创建链表,函数调用部分#includestdio.h
#includewindows.h
#include stdio.h
#include malloc.h
#include stdlib.h
//定义数据类型名称
typedef int DataType;
#define flag -1//定义数据输入结束的标志数据
//单链表结点存储结构定义
typedef struct Node
{
DataType data;
struct Node *next;
}LNode ,*LinkList;
//建立单链表子函数
LNode *Create_LinkList()
{
LNode *s,*head,*L;int i=0,x;//定义指向当前插入元素的指针
while(1)
{
scanf("%d",x);
if(-1==x)
{return head;
break;}
s= (LNode *)malloc(sizeof(LNode));//为当前插入元素的指针分配地址空间
s-data =https://www.04ip.com/post/x;

推荐阅读