C语言的 链表!! 请求帮忙
共两条:1、先建立一个整型数的单链表,然后统计单链表中数据元素为0的个数
2、先建立一个字母单链表并输出到屏幕上,再试着插入一个字母(例如:将I插入到L之后)
[解决办法]
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode //链表定义...
{
int data ; //数据域..
struct lnode *next ; //指针域..
} lnode , *linklist ;
int initlink(linklist *l) //新键链表..l为接收链表 ,,k为想插入数的个数..
{
(*l)=(linklist )malloc(sizeof(lnode)); //开空间....
if(*l==NULL)
return 0;
(*l)-> next=NULL; // 链表为空....
return 1;
}
int createlink(linklist *l) //建立链表.. ( 算法:是头插法.....)
{
linklist head=NULL; //头指针...
int i,a; //i是用来控制输入的个数...
printf( "请输入10个数...\n ");
for(i=0;i <10;i++)
{
(*l)=(linklist )malloc(sizeof(lnode)); //用循环开每个接点的空间...
scanf( "%d ",&a);
(*l)-> data=a; //把输入的元素放到的结点上...
(*l)-> next=head ;
head=(*l); //进行每个结点的的连接...
}
return 1;
}
[解决办法]
给个例子:
或者楼主看看 数据结构的书吧,有例子滴
单链表的建立
有了动态内存分配的基础,要实现链表就不难了。
所谓链表,就是用一组任意的存储单元存储线性表元素的一种数据结构。链表又分为单链表、双向链表
和循环链表等。我们先讲讲单链表。所谓单链表,是指数据接点是单向排列的。一个单链表结点,其结构类
型分为两部分:
1、数据域:用来存储本身数据
2、链域或称为指针域:用来存储下一个结点地址或者说指向其直接后继的指针。
例:
typedef struct node
{
char name[20];
struct node *link;
}stud;
这样就定义了一个单链表的结构,其中char name[20]是一个用来存储姓名的字符型数组,指针*link是
一个用来存储其直接后继的指针。
定义好了链表的结构之后,只要在程序运行的时候爱数据域中存储适当的数据,如有后继结点,则把链
域指向其直接后继,若没有,则置为NULL。
下面就来看一个建立带表头(若未说明,以下所指链表均带表头)的单链表的完整程序。
#include <stdio.h>
#include <malloc.h> /*包含动态内存分配函数的头文件*/
#define N 10 /*N为人数*/
typedef struct node
{
char name[20];
struct node *link;
}stud;
stud * creat(int n) /*建立单链表的函数,形参n为人数*/
{
stud *p,*h,*s; /* *h保存表头结点的指针,*p指向当前结点的前一个结点,*s指向当前结点*/
int i; /*计数器*/
if((h=(stud *)malloc(sizeof(stud)))==NULL) /*分配空间并检测*/
{
printf( "不能分配内存空间! ");
exit(0);
}
h-> name[0]= '\0 '; /*把表头结点的数据域置空*/
h-> link=NULL; /*把表头结点的链域置空*/
p=h; /*p指向表头结点*/
for(i=0;i <n;i++)
{
if((s= (stud *) malloc(sizeof(stud)))==NULL) /*分配新存储空间并检测*/
{
printf( "不能分配内存空间! ");
exit(0);
}
p-> link=s; /*把s的地址赋给p所指向的结点的链域,这样就把p和s所指向的结点连接起来了*/
printf( "请输入第%d个人的姓名 ",i+1);
scanf( "%s ",s-> name); /*在当前结点s的数据域中存储姓名*/
s-> link=NULL;
p=s;
}
return(h);
}
main()
{
int number; /*保存人数的变量*/
stud *head; /*head是保存单链表的表头结点地址的指针*/
number=N;
head=creat(number); /*把所新建的单链表表头地址赋给head*/
}
这样就写好了一个可以建立包含N个人姓名的单链表了。写动态内存分配的程序应注意,请尽量对分配是
否成功进行检测。
[解决办法]
第一个的,第二个尝试着自己做下。。。。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node
{
int num;
struct Node *next;
};
struct Node *creat()
{
int x;
struct Node *p, *q, *head;
head = ( struct Node *)malloc(sizeof(struct Node));
head-> next = NULL;
p = head;
scanf( "%d ", &x );
while( x != -1 )
{
q = ( struct Node *)malloc( sizeof( struct Node ) );
q-> num = x;
q-> next = NULL;
p-> next = q;
p = q;
scanf( "%d ", &x );
}
return ( head );
}
void Print( struct Node *head )
{
struct Node *p;
int count = 0;
p = head-> next;
while( p != NULL )
{
if ( p-> num == 0 )
count++;
p = p-> next;
}
printf( "%d ", count );
}
int main()
{
struct Node *head;
printf( "Please input link value with -1 end:\n " );
head = creat();
printf( "the number of 0 in link is: " );
Print(head);
printf( "\n " );
system( "pause " );
return 0;
}