實驗報告: 線性表的基本操作及應用
實驗內容
基本要求:
(1)實現單鏈表的創建;(2)實現單鏈表的插入;(3)實現單鏈表的刪除
(4)實現單鏈表的查找;(5)實現單鏈表的顯示;
/*Name:Linklist operation.cpp Author:XDate:2020/3/13 Description: 線性表的基本操作及應用
*/
#include<stdio.h>
#include<stdlib.h> //分配數據
#define ERROR 0;
#define OK 1;typedef int ElemType;
typedef int status;typedef struct LNode
{ElemType data;struct LNode *next;
}LNode,*LinkList;//建立線性表LA ,頭插法
status CreatList_LA(LinkList &LA,int n)
{LNode *p;int i;LA=(LinkList)malloc(sizeof(LNode));LA->next=NULL;for(i=n;i>0;--i){p=(LinkList)malloc(sizeof(LNode));scanf("%d",&p->data);p->next=LA->next;LA->next=p;}return OK;
}//建立線性表LB
status CreakList_LB(LinkList &LB,int n)
{LNode *p;status i;LB=(LinkList)malloc(sizeof(LNode));LB->next=NULL;for(i=n;i>0;--i){p=(LinkList)malloc(sizeof(LNode));scanf("%d",&p->data);p->next=LB->next;LB->next=p;}return OK;
}//在第i個結點前插入e
status ListInsert_LA(LinkList &LA,status i,ElemType e)
{LNode *p,*s; //等同于 LinkList p,s;status j;p=LA;j=0;while(p&&j<i-1){p=p->next;++j; //計數器 }if(!p||j>i-1)return ERROR;s=(LinkList)malloc(sizeof(LNode));s->data=e;s->next=p->next;p->next=s;return OK;
}//刪除第i個結點,值代入e
status ListDelete_LA(LinkList &LA,int i,ElemType &e)
{LNode *p,*q;status j;p=LA;j=0;while(p||j<i-1){p=p->next;++j;}if(p->next==NULL||j>i-1)return ERROR;q=p->next;p->next=q->next;e=q->data; free(q);return OK;
} //查找到第i個元素,用e返回
status GetElem_LA(LinkList LA,int i,ElemType e)
{ LNode *p;p=LA;status j;j=0;while(p&&j<i-1){p=p->next;++j;}if(!p||j>i)return ERROR;e=p->data;return OK;} //合并線性表LA和LB
status MergeList_L(LinkList &LA,LinkList &LB,LinkList &LC)
{LNode *pa,*pb,*pc;pa=LA->next;pb=LB->next;LC=pc=LA;while(pa&&pb){if(pa->data<=pb->data) {pc->next=pa;pc=pa;pa->next;}else{pc->next=pb;pc=pb;pb=pb->next;}pc->next=pa?pa:pb;} free(LB);}//輸出鏈表
status printfList_L(LinkList &L)
{LNode *p;int i;p=L->next;while(p){printf("%d ",p->data);p=p->next;}
}int main()
{ElemType e ;LinkList LA,LB,LC;status i,n;printf("輸入向所創建LA鏈表中插入幾個結點,n為:");scanf("%d",&n); printf("輸入鏈表的結點數據:");CreatList_LA(LA,n) ;printf("輸入向所創建LB鏈表中插入幾個結點,n為:");scanf("%d",&n); printf("輸入鏈表的結點數據:");CreakList_LB(LB,n); printf("輸出鏈表LA為:");printfList_L(LA);printf("\n輸出鏈表LB為:");printfList_L(LB);printf("\n輸入在鏈表第幾個位置插入結點,i,e為:");scanf("%d%d",&i,&e);ListInsert_LA(LA,i,e);printf("\n插入后使出的鏈表為:");printfList_L(LA);printf("\n輸入在鏈表第幾個位置刪除結點,i為:"); scanf("%d",&i);ListDelete_LA(LA,i,e);printf("\n刪除后的鏈表LA為:");printfList_L(LA);printf("刪除的第%d個結點所儲存的元素為:%f",i,e);printf("\n輸入想查找第幾個元素結點,i為:");scanf("%d",&i);GetElem_LA(LA,i,e);printf("\n查找到的第i個元素為:");printf("%d",e);printf("\n合并之后的鏈表為:");MergeList_L(LA,LB,LC);printfList_L(LC);return OK;
}
【記得引用符&與變量名稱間有空格】
【定義的函數數據類型要與其中數據的數據類型一值】