【データ構造】リニアチェーン(シングルチェーン表)
4451 ワード
//
// main.cpp
// LinkList
//
// Created by T.P on 2019/1/31.
// Copyright © 2019 T.P. All rights reserved.
//
#include
#include //malloc free
#define TRUE 1
#define FALSE 0
#define OK 0
#define ERROR -1
#define INFEASIBLE -1 //
#define OVERFLOW -2 //
typedef struct LNode{//LNode( )
int data;
struct LNode *next=NULL;
}LNode,*LinkList;//LNode("struct LNode" )
// L( ) | L [ ( 0 )]
// | L [ L ]
int InitList_L(LinkList &L){// L, " "
L=(LinkList)malloc(sizeof(LNode));// ,
L->data=0;
L->next=NULL;
if(!L)
exit(OVERFLOW);
return 0;
}
// L[ ] | L [ ( 0 )]
// | L +
int FreeList_L(LinkList &L){// L, " "
LinkList temporary=L;
while(temporary->next!=NULL){
temporary=L->next;
L->next=temporary->next;
free(temporary);
}
free(L);
return 0;
}
//
int Print_L(LinkList &L){// L, " "
LinkList p=L;//p ( )
while (p->next) {// y ( )
printf("%d ",p->next->data);
p=p->next;
}
printf("
");
return 0;
}
//ALGORITHM_2_8
// L | L [ ( 0 )]
// e L i | i 1
int GetElem_L(LinkList &L,int i,int &e){// L, " "
LinkList p=L;//p
int j=0;// 0
while (p&&jnext;
++j;
}
if(!p||i<=0)//p /i | (j>i)??
return ERROR;
e=p->data;
return OK;
}
//ALGORITHM_2_9
// L | L [ ( 0 )]
// i e | i 1
int InsertList_L(LinkList &L,int i,int e){// L, " "
LinkList p=L;//p ( )
int j=0;// 0
while (p&&jnext;
++j;
}
if(!p||i<=0)//p /i | ?? if(!p||j>i-1)
return ERROR;
LinkList s=(LinkList)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return 0;
}
//ALGORITHM_2_10
// L | L [ ( 0 )]
// i e | i 1
int DeleteList_L(LinkList &L,int i,int &e){// L, " "
LinkList p=L;//p ( )
int j=0;// 0
while (p&&jnext;
++j;
}
if(!p||i<=0)//p /i | ?? if(!p||j>i-1)
return ERROR;
LinkList s=p->next;
p->next=s->next;
e=s->data;
free(s);
return 0;
}
//ALGORITHM_2_11
// L( ) | L [ ( 0 )]
// n
int CreateList_L(LinkList &L,int n){// L, " "
L=(LinkList)malloc(sizeof(LNode));// ,
L->data=0;
L->next=NULL;
for(int i=n;i>0;--i){
LinkList p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
return 0;
}
//ALGORITHM_2_12
// La,Lb ( )
// La,Lb Lc,Lc s ( )
int MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc){// L, " "
Lc=(LinkList)malloc(sizeof(LNode));// ,
Lc->data=0;
Lc->next=NULL;
LinkList La_p=La->next;//
LinkList Lb_p=Lb->next;
LinkList Lc_p=Lc;
while(La_p!=NULL&&Lb_p!=NULL){// Lc next
if(La_p->datadata){
Lc_p->next=La_p;
Lc_p=Lc_p->next;
La_p=La_p->next;
}
else{
Lc_p->next=Lb_p;
Lc_p=Lc_p->next;
Lb_p=Lb_p->next;
}
}
if(La_p!=NULL) // Lc_p->next=La_p?La_p:Lb_p
Lc_p->next=La_p;
else
Lc_p->next=Lb_p;
return 0;
}
int main(int argc, const char * argv[]) {
printf("OK
");
//LinkList a;// ,
//LNode a;//
// : " "
// :
//LinkList a;
//InitList_L(a);
LinkList a;
LinkList b;
LinkList c;
CreateList_L(a,4);
Print_L(a);
printf("OK
");
CreateList_L(b, 5);//
Print_L(b);
printf("OK
");
MergeList_L(a,b,c);
Print_L(c);
return 0;
}