链表结构

来源:互联网 发布:读懂php wsdl中方法 编辑:程序博客网 时间:2024/05/30 23:13

把以前学的链表整理一下,配上刚画的图演示。


#include <stdio.h>#include <malloc.h>struct node{int data;struct node * pnext;};struct node * input_list(void){int len;int i;struct node * phead = (struct node *)malloc(sizeof(struct node));if(NULL == phead){printf("动态内存分配错误\n");exit(-1);}struct node * ptail = phead;ptail->pnext = NULL;//链表尾结构体的地址为空printf("输入链表长度\nlen = ");scanf("%d", &len);  int val;for(i=0;i<len;i++){printf("请输入第%d个节点的值: ", i+1);scanf("%d", &val);struct node * pnew = (struct node *)malloc(sizeof(struct node));if(NULL == pnew){printf("动态内存分配错误\n");exit(-1);}ptail->pnext = pnew;ptail = pnew;pnew->pnext = NULL;pnew->data = val;} return phead;}void output_list(struct node * phead){while(phead->pnext != NULL){printf("%d\n", phead->pnext->data);phead = phead->pnext;}return;}void free_list(struct node * phead){struct node * plist = NULL;do{plist = phead;phead = phead->pnext;free(plist);}while(phead != NULL); return; }int main(void){struct node * phead = NULL;//结构体指针地址为空 phead = input_list();//创建链表返回链表头的地址 output_list(phead);free_list(phead);//释放动态内存 return 0;}



0 0