单链表(头插法,尾插法创建,顺序输出链表,并返回链表长度)
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define LENG sizeof(struct node)//结点所占单元数
struct node{
int data;
struct node *next;
};
int main()
{
struct node*create1();/*尾插法建立单链表*/
struct node*create2();//头插法建立单链表
int length(struct node*head);//返回单链表的长度,并输出各节点的值
struct node*head1,*head2;
head1=create1();
head2=create2();
int leng1=length(head1);
printf("\n");
printf("单链表1的长度为:%d",leng1);
printf("\n");
int leng2=length(head2);
printf("\n");
printf("单链表2的长度为:%d",leng2);
return 0;
}
struct node *create1(){
struct node*head,*tail,*p;
int e;
head=(struct node *)malloc(LENG);//生成表头结点
tail=head; //尾指针只想表头
printf("please input a integer number:");
scanf("%d",&e); //输入第一个数
while(e!=0){
p=(struct node *)malloc(LENG);//生成新节点
p->data=e;
tail->next=p; //新节点链接到表尾
tail=p; //尾指针指向新节点
printf("please input a integer number:");
scanf("%d",&e);
}
tail->next=NULL; //尾节点的next域置为空指针
return head; //返回头指针
}
struct node *create2(){
struct node *head,*p;
int e;
head=(struct node*)malloc(LENG);
head->next=NULL;
printf("please input a integer number:");
scanf("%d",&e);
while(e!=0){
p=(struct node *)malloc(LENG);
p->data=e;
p->next=head->next;
head->next=p;
printf("please input a integer number:");
scanf("%d",&e);
}
return head;
};
int length(struct node*head){
int leng=0;
struct node*p;
p=head->next; //p指向首结点
while(p!=NULL){
printf("%d",p->data);
printf(" ");
leng++;
p=p->next;
}
return leng;
}
运行结果: