单链表的建立和打印
#include <stdio.h>
#include <stdlib.h>//定義鏈表數據結構
struct node
{int num;struct node *next;
};//函數聲明
struct node *creat(struct node *);
void print(struct node *);void main()
{struct node *head;head = NULL; //創建一個空表head = creat(head); //創建單鏈表print(head); //打印單鏈表
}struct node *creat(struct node *head)
{struct node *p1,*p2;int i = 1;//利用malloc函數向系統申請節點p1 = p2 = (struct node *)malloc(sizeof(struct node)); //申請節點printf("輸入大于0的值,小于等于0則結束,值的存放地址為:p1_addr = %d\n",p1);scanf("%d",&p1->num);p1->next = NULL;while(p1->num > 0){if(head == NULL)head = p1;elsep2->next = p1;p2 = p1;p1 = (struct node *)malloc(sizeof(struct node));p1->next = NULL;//置空i++;printf("輸入大于0的值,小于等于0則結束,值的存放地址為:p%d_addr = %d\n",i,p1);scanf("%d",&p1->num);}free(p1); p1 = NULL;p2->next = NULL;printf("輸入結束\n");return head;
}void print(struct node *head)
{struct node *tmp;tmp = head;printf("鏈表打印開始!!!\n");while(tmp != NULL){printf("輸入的值為:num = %d,地址為:addr = %d\n",tmp->num,tmp);tmp = tmp->next;}printf("鏈表打印結束!!!\n");
}
運行結果:?
總結
- 上一篇: 写出程序删除链表中的所有接点
- 下一篇: 编译时“-nostdlib”的使用