链表是一种常见的数据结构,它有一个头指针,链表中信息的输出就是靠头指针来引出。链表的每个元素都包括数据部分和指针部分。
创建链表:
想要创建一个链表首先得定义一个结构体,结构体就是链表的数据部分,结构体中要包含所需要的数据和指向下一个元素的结构体类型指针。
代码如下:
struct notes
{
int n;
struct notes *next;
};
接下来就是创建链表的代码
int cnt;//定义一个整型变量用来计算结点的数量
struct notes*create()
{
struct notes *pnew,*pend;
struct notes *phead=NULL;//让头指针指向为空。
cnt = 0;
pnew = pend = (struct notes*)malloc(sizeof (struct notes));
scanf("%d",&pnew->n );//输入第一个元素
while(pnew->n != 0){
cnt++;
if(cnt == 1){
pnew->next = phead;//让第一个元素的下一个节点指向为空
pend = pnew;//让旧结点等于新的结点
phead = pnew;//让头指针指向第一个结点
}else{
pnew->next = NULL;
pend->next = pnew;//让上一个结点指向下一个结点
pend = pnew;
}
pnew=(struct notes*)malloc(sizeof(struct notes));
scanf("%d",&pnew->n );
}
free(pnew);//释放数据为零的空间
return phead;//返回头指针
}
接下来就是遍历链表了
void print(struct notes*phead)//创建一个输出函数,将头指针代入
{
struct notes *ptemp;//定义一个临时指针用来输出元素
ptemp = phead;
while(ptemp != NULL){
printf("%d\n",ptemp->n );
ptemp = ptemp->next ;//让元素自身等于它指向的下一个元素
}
}
以下就是链表创建与遍历的全貌了
#include<stdio.h>
#include<stdlib.h>
struct notes{
int n;
struct notes *next;
};
int cnt;
struct notes*create()
{
struct notes *pnew,*pend,*phead=NULL;
cnt = 0;
pnew = pend = (struct notes*)malloc(sizeof (struct notes));
scanf("%d",&pnew->n );
while(pnew->n != 0){
cnt++;
if(cnt == 1){
pnew->next = phead;
pend = pnew;
phead = pnew;
}else{
pnew->next = NULL;
pend->next = pnew;
pend = pnew;
}
pnew=(struct notes*)malloc(sizeof(struct notes));
scanf("%d",&pnew->n );
}
free(pnew);
return phead;
}
void print(struct notes*phead)
{
struct notes *ptemp;
ptemp = phead;
while(ptemp != NULL){
printf("%d\n",ptemp->n );
ptemp = ptemp->next ;
}
}
int main()
{
struct notes *phead;
phead = create();
print(phead);
printf("\n");
struct notes *p,*q;
p=q=phead;
while(p!=NULL){
q=q->next ;
free(p);
p=q;
}
return 0;
}
(创建链表的函数也可以不返回任何值,但头指针要设置为全局变量,代码如下:)
#include<stdio.h>
#include<stdlib.h>
struct notes{
int n;
struct notes *next;
};
struct notes *phead = NULL;//设置头指针为全局变量。
int cnt;
void create() //函数不返回任何值。
{
struct notes *pnew,*pend;//这里也不需要再定义头指针。
cnt = 0;
pnew = pend = (struct notes*)malloc(sizeof (struct notes));
scanf("%d",&pnew->n );
while(pnew->n != 0){
cnt++;
if(cnt == 1){
pnew->next = phead;
pend = pnew;
phead = pnew;//让头指针在这等于第一个节点;
}else{
pnew->next = NULL;
pend->next = pnew;
pend = pnew;
}
pnew=(struct notes*)malloc(sizeof(struct notes));
scanf("%d",&pnew->n );
}
free(pnew);
//不需要返回。
}
void print(struct notes*phead)
{
struct notes *ptemp;
ptemp = phead;
while(ptemp != NULL){
printf("%d\n",ptemp->n );
ptemp = ptemp->next ;
}
}
int main()
{
create();//在这直接调用函数输入。函数中头指针会指向第一个节点。
print(phead);
printf("\n");
struct notes *p,*q;
p=q=phead;
while(p!=NULL){
q=q->next ;
free(p);
p=q;
}
return 0;
}