#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}Node,*Linklist;
Node *creat_List_a()//尾插法建立單鏈表
{
Linklist L;
Node *p;
int temp;
L=(Linklist)malloc(sizeof(Node));
L->next=NULL;
scanf("%d",&temp);
while(temp!=-1)
{
p=(Linklist)malloc(sizeof(Node));
p->data=temp;
p->next=L->next;
L->next=p;
scanf("%d",&temp);
}
return L;
}
Node * creat_List_b() //頭插法建立單鏈表
{
Linklist L;
int temp;
Node *p;
Node *r;
L=(Linklist)malloc(sizeof(Node));
L->next=NULL;
r=L;
scanf("%d",&temp);
while(temp!=-1)
{
p=(Linklist)malloc(sizeof(Node));
p->data=temp;
r->next=p;
r=p;
scanf("%d",&temp);
}
r->next=NULL;
return L;
}
int main()
{
Linklist head;
int i;
printf("請輸入一個整數,選擇創建鏈表方式:");
scanf("%d",&i);
if(i==1)
{
head=creat_List_a();
}
else
{
head=creat_List_b();
}
Node *p;
p=head->next;
while(p!=NULL)
{
printf("%2d",p->data);
p=p->next;
}
return 0;
}
c語言實現單鏈表創建和遍歷
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.