c语言创建单链表 遍历单链表

/************************************************************************/ /* huziaa@gmail.com/ */ /************************************************************************/ #include <stdlib.h> /*包含malloc( ) 的头文件*/ #include <stdio.h> struct node /*链表节点的结构*/ { int num; struct node *next; }; struct node * creat(struct node *head); void print(struct node * head); int main () { struct node *head; /*定义头指针*/ head=NULL;/*建一个空表*/ head=creat(head);/*创建单链表*/ print(head);/*打印单链表*/ return 0; } /******************************************/ /*数函返回的是与节点相同类型的指针*/ struct node * creat(struct node *head) { int i=0; struct node*p1,*p2; p1=p2=(struct node*)malloc(sizeof(struct node)); /*申请新节点*/ memset(p1, 0, sizeof(struct node)); scanf("%d",&p1->num); /*输入节点的值*/ p1->next=NULL; /*将新节点的指针置为空*/ while(p1->num>0) /*输入节点的数值大于0*/ { if(head==NULL) head=p1; /*空表,接入表头*/ else p2->next=p1; /*非空表,接到表尾*/ p2=p1; p1=(struct node*)malloc(sizeof(struct node));/*请申下一个新节点*/ memset(p1, 0, sizeof(struct node)); scanf("%d",&p1->num); /*输入节点的值*/ p1->next=NULL; i++; } printf("\n total : %d\n",i); return head; /*返回链表的头指针*/ } /*******************************************//*输出以head为头的链表各节点的值*/ void print(struct node*head){ struct node *temp; temp=head; /*取得链表的头指针*/ while(temp!=NULL) /*只要是非空表*/ { printf("%6d\n",temp->num); /*输出链表节点的值*/ temp=temp->next; /*跟踪链表增长*/ } }

这就是c语言单链表的创建和遍历,接着学习删除,插入.........

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值