用c语言创建链表

Python06

用c语言创建链表,第1张

主函数这里

Linklist List

printf("输入创建链表的长度:")

scanf("%d",&num)

CreateList_H(List,num) //创建链表

改为 

LNode List

printf("输入创建链表的长度:")

scanf("%d",&num)

CreateList_H(&List,num) //创建链表

函数内在堆上分配好内存,但是 没有传递到栈上

另外 你的变量名很迷人

#include<stdio.h>

#include<stdlib.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=headhead=head->nextfree(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=headi<ni++ ) {

t=(DATA*)malloc(sizeof(DATA)) if ( !t ) { printf("error")return head }

scanf("%d",&t->number) t->next=NULLtial->next=t tial=t

}

return head

}

C语言创建单链表如下:

#include"stdio.h"

#include"stdlib.h"

#include"malloc.h"

#include "iostream.h"

typedef struct node

{

int  data

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=c

for(int i=2i<=ni++)

{

s=(List)malloc(sizeof(node))

printf("请输入第%d个数据:",i)

scanf("%d",&c)

s->data=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。尾插法最先得到的是 头结点。