1、从键盘输入10个整数放入链表,要求链表中的元素与输入顺序一致,然后输出该链表。
实验源程序:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int Data;
struct Node*next;
};
struct Node* creat(){
struct Node*L;
L=(struct Node*)malloc(sizeof(struct Node));
L->next=NULL;
return L;
}
void Insert(struct Node *L,int N){
struct Node*p,*q;
p=L;
while(p->next!=NULL)
p=p->next;
q=malloc(sizeof(struct Node));
q->Data=N;
q->next=p->next;
p->next=q;
q->next=NULL;
}
void print(struct Node*L){
struct Node*p;
p=L->next;
while(p!=NULL) {
printf("%d ",p->Data);
p=p->next;
}}
int main(){
struct Node*L;
int i,n;
L=creat();
for(i=0;i<10;i++){
scanf("%d",&n);
Insert(L,n);
}
print(L);
return 0;
}
2、随机生成100个随机整数并放入一个链表中,要求链表中的元素按从小到大顺序排列,然后输出该链表。
实验源程序:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node{
int Data;
struct Node*Next;
};
void Print(struct Node *L){
struct Node *q;
q=L->Next;
while(q!=NULL){
printf("%d ",q->Data);
q=q->Next;
}
}
void Insert(struct Node*L,int n){
struct Node*p,*q;
p=L;
q=(struct Node*)malloc(sizeof(struct Node));
while(p->Next!=NULL&&p->Next->Data<n){
p=p->Next;
}
q->Data=n;
q->Next=p->Next;
p->Next=q;
}
int main(){
struct Node *L;
L=(struct Node*)malloc(sizeof(struct Node));
L->Next=NULL;
srand((int)time(NULL));
int i;
for(i=0;i<100;i++){
Insert(L,rand()%100);
}
Print(L);
return 0;
}