今天小编在这分享一段数据结构中线性表实现的源码,希望能帮到各位。
#include<stdio.h>
#include<malloc.h>
struct node{ //定义相应的结构体;
int data;
struct node *pnext;
};
struct node *phead = NULL;//定义·一个头结点指针的全局变量,方便以后调用!
void createHeadNode();
void createNewNode(struct node *phead);
void showList(struct node *phead);
int main(){
createHeadNode();
createNewNode(phead);
showList(phead);
return 0;
}
void createHeadNode(){//给头节点分配空间;
phead = (struct node *)malloc(sizeof(struct node));
phead->pnext = NULL;//防止野指针的出现;
if (!phead){
printf("分配空间错误,头节点创建失败!\n");
return;
}
}
void createNewNode(struct node *phead){//添加新的结点;
struct node *phead1 = phead;
struct node *pnew = NULL;
for (int i = 0; i < 5; i++){
pnew = (struct node*)malloc(sizeof(struct node));
if (!pnew){
printf("分配空间错误,新节点创建失败!\n");
}
else{
pnew->data = i;//为了方便测试,直接把data给写死;
pnew->pnext = NULL;
phead1->pnext = pnew;//通过头指针连接各个结点;
phead1 = phead1->pnext;//头指针后移,始终保证它在最后一个节点上!
}
}
}
void showList(struct node *phead){//打印链表的各个结点;
struct node *phead2 = phead->pnext;
while (phead2 != NULL){
printf("%d ", phead2->data);
phead2 = phead2->pnext;
}
}