链表头插法,尾插法以及带头结点输出,不带头结点输出
首先是头插法
#include"stdio.h"
#include"stdlib.h"
typedef struct we
{
int data;
struct we *next;
}qwe;
void shuchu(qwe *head)
{
qwe *p;
printf("不带头结点的链表为:\n");//注意printf的次序
p=head;
for(;p!=NULL;)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
qwe * yunxing(qwe *head)
{
qwe *p;
int x;
printf("请输入不为零的数\n");
scanf("%d",&x);
for(;x!=0;)
{
p=(qwe *)malloc(sizeof(qwe));
p->data=x;
p->next =head;
head=p;
scanf("%d",&x);
}
return head;
}
int main()
{
qwe *p,*head;
head=NULL;
p=yunxing(head);
shuchu(p);
return 0;
}
以上的shuchu函数用的就是不带头结点的输出方式(p=head)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
接下来是尾插法
#include"stdio.h"
#include"stdlib.h"
typedef struct we
{
int data;
struct we *next;
}qwe;
void shuchu(qwe *head)
{
qwe *p;
printf("带头节点的单链表为:\n");
p=head->next ;
for(;p!=NULL;)
{
printf("%d\t",p->data );
p=p->next;
}
printf("\n");
}
qwe * yunxing(qwe *head)
{
int x;
qwe *t,*last;
t=(qwe *)malloc(sizeof(qwe));
head=t;
last=t;
t->next =NULL;
printf("请输入一个数:\n");
scanf("%d",&x);
for(;x!=0;)
{
t=(qwe *)malloc(sizeof(qwe));
t->data=x;
t->next =NULL;
last->next =t;
last=t;
scanf("%d",&x);
}
return head;
}
int main()
{
qwe *p,*head;
head=NULL;
p=yunxing(head);
shuchu(p);
return 0;
}
这个shuchu函数用的就是带头结点的输出方式(p=head->next)
还没有评论,来说两句吧...