#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define len sizeof(struct list)
struct list
{
int data;
struct list *next;
};
struct list *la,*lb;
//初始化連結清單
struct list * InitList()
{
struct list *head;
head=(struct list *)malloc(len);
return head;
}
//為連結清單指派
struct list * ListInsert(struct list* &la)
{
struct list *p1,*head;
int n;
head=la;
printf("請輸入資料的個數\n");
scanf("%d",&n);
printf("請輸入資料,用空格分開\n");
while(n--)
{
p1=(struct list*)malloc(len);
scanf("%d",&p1->data);
p1->next=NULL;
la->next=p1;
la=p1;
}
return head;
}
//向連結清單中取元素
void GetElem(struct list * la)
{
printf("請輸入你要取得值的位置\n");
int n;
scanf("%d",&n);
while(la->next&&n)
{
n--;
la=la->next;
}
if(n)
printf("輸入的位置超對外連結表範圍\n");
else
printf("所處位置的元素為%d\n",la->data);
}
//向連結清單指定位置插入元素
void InsertElem(struct list * la)
{
struct list* pos;
printf("請輸入你要插入的位置和元素\n");
int n,x;
scanf("%d %d",&n,&x);
while(la->next&&n)
{
n--;
pos=la;
la=la->next;
}
if(n)
printf("輸入的位置超對外連結表範圍\n");
else
{
struct list * p1;
p1=(struct list*)malloc(len);
p1->data=x;
p1->next=pos->next;
pos->next=p1;
printf("插入成功\n");
}
}
//合并連結清單
bool UnionList(struct list *pa,struct list *pb)
{
struct list *head;
head=pa;
while(pa->next){
pa=pa->next;
}
pa->next=pb->next;
printf("合并後的連結清單為:\n");
while(head->next){
printf("%d ",head->next->data);
head=head->next;
}
printf("\n");
}
int main(){
while(1){
printf("************************************************************\n");
printf("* 請輸入你要實作的功能前的序号 *\n");
printf("* 1 初始化連結清單 *\n");
printf("* 2 對連結清單進行指派 *\n");
printf("* 3 向連結清單中取值 *\n");
printf("* 4 向連結清單中插入元素 *\n");
printf("* 5 歸并連結清單 *\n");
printf("* 6 退出程式 *\n");
printf("************************************************************\n");
int x;
scanf("%d",&x);
if(x==1){
printf("請輸入你要初始化的連結清單a,b\n\n");
getchar();
char ch;
ch=getchar();
if(ch=='a'){
la=InitList();
if(!la)
printf("初始化失敗\n\n");
else{
la->next=NULL;
printf("初始化成功\n\n");
}
}
else if(ch=='b'){
lb=InitList();
if(!lb)
printf("初始化失敗\n\n");
else{
lb->next=NULL;
printf("初始化成功\n\n");
}
}
else
printf("輸入錯誤\n\n");
}
else if(x==2){
printf("請輸入你要進行指派的連結清單a或者b\n\n");
getchar();
char ch=getchar();
if(ch=='a') {
if(!la)
printf("請先對連結清單a進行初始化\n\n");
else
la=ListInsert(la);
}
else if(ch=='b'){
if(!lb)
printf("請先對連結清單b進行初始化\n\n");
else
lb=ListInsert(lb);
}
}
else if(x==3){
printf("請輸入你要進行取值的連結清單a或者b\n\n");
getchar();
char ch=getchar();
if(ch=='a') {
if(!la)
printf("請先對連結清單a進行初始化\n\n");
else
GetElem(la);
}
else if(ch=='b'){
if(!lb)
printf("請先對連結清單b進行初始化\n\n");
else
GetElem(lb);
}
}
else if(x==4){
printf("請輸入你要進行插入的連結清單a或者b\n\n");
getchar();
char ch=getchar();
if(ch=='a') {
if(!la)
printf("請先對連結清單a進行初始化\n\n");
else
InsertElem(la);
}
else if(ch=='b'){
if(!lb)
printf("請先對連結清單b進行初始化\n\n");
else
InsertElem(lb);
}
}
else if(x==5){
if(!la){
printf("請先初始化連結清單a\n");
break;
}
if(!la){
printf("請先初始化連結清單b\n");
break;
}
UnionList(la,lb);
}
else
break;
}
return 0;
}