1.头插法
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
struct LNode *CreatLNode(){
int x;
int LNode_len=0;
LNode *head;
LNode *s;
head=(struct LNode*)malloc(sizeof(struct LNode));
printf("请输入数据(9999结束)\n");
scanf("%d",&x);
while(x!=9999){
s=(struct LNode*)malloc(sizeof(struct LNode));
s->data=x;
s->next=head->next;
head->next=s;
LNode_len++;
head->data=LNode_len;
scanf("%d",&x);
}
return head;
};
LNode print(LNode *head){
LNode *p=head->next;
int i;
for(i=0;i<head->data;i++){
printf("%3d",p->data);
p=p->next;
}
}
int main()
{
LNode *p;
p=CreatLNode();
print(p);
return 0;
}
2.尾插法
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
struct LNode *CreatLNode(){
LNode *head;
LNode *p1,*p2;
int LNode_len=0;
int x;
head=(struct LNode*)malloc(sizeof(struct LNode));
p1=p2=head;
printf("请输入数据(9999结束)\n");
scanf("%d",&x);
while(x!=9999){
p1=(struct LNode*)malloc(sizeof(struct LNode));
p1->data=x;
p2->next=p1;
p2=p1;
LNode_len++;
head->data=LNode_len;
scanf("%d",&x);
}
p1->next=NULL;
return head;
};
LNode print(LNode *head){
LNode *p=head->next;
int i;
for(i=0;i<head->data;i++){
printf("%3d",p->data);
p=p->next;
}
}
int main()
{
LNode *p;
p=CreatLNode();
print(p);
return 0;
}