线性表的基本操作
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <conio.h> 4 #include <string.h> 5 #define OK 1 6 #define ERROR -1 7 8 typedef int ElemType; 9 typedef int status ; 10 11 typedef struct 12 { 13 ElemType *elem; 14 int length ; 15 int size ; 16 }SqList; 17 18 status equal(ElemType a,ElemType b) 19 { 20 return a==b; 21 } 22 status init_List(SqList &L) //表初始化 23 { 24 L.elem=(ElemType*)malloc(100*sizeof(ElemType)); 25 if(!L.elem) return 0 ; 26 L.length=0 ; 27 L.size=100 ; 28 return OK ; 29 } 30 31 32 int locateList(SqList L,int e,int (*compare)(int ,int)) 33 { 34 int i=1 ; 35 while( i<=L.length) 36 { 37 if(compare(L.elem[i-1],e)) return i ; 38 i++ ; 39 } 40 return 0 ; 41 } 42 43 44 45 status getelem(SqList L,int i,ElemType &e)//取表中第i个数据给e 46 { 47 e=L.elem[i-1]; 48 return OK ; 49 } 50 51 52 53 void traveList(SqList L) 54 { 55 int i ; 56 for(i=1;i<=L.length ;i++) 57 printf("%d ",L.elem[i-1]); 58 59 } 60 61 status insertlist(SqList &L,int i,ElemType e)//向表中第i个位置插入数据 62 { 63 ElemType *newbase,*p,*q ; 64 if(i<1||i>L.length+1) return 0 ; 65 if(L.length>=L.size) 66 { 67 newbase=(ElemType*)realloc(L.elem,(L.size+20)*sizeof(ElemType)); 68 if(!newbase) return 0; 69 L.elem=newbase; 70 L.size+=20 ; 71 } 72 q=L.elem+i-1; 73 for(p=L.elem+L.length-1;p>=q;p--) 74 *(p+1)=*p ; 75 *q=e ; 76 L.length++ ; 77 return OK ; 78 } 79 80 81 void unionlist(SqList &LA,SqList LB)//求LA=LA U LB 82 { 83 //将所有在线性表LB中但不在LA中的数据元素插入到LA中 84 int LA_len,LB_len,i,e; 85 LA_len=LA.length; LB_len=LB.length;//求线性表的长度 86 for(i=1;i<=LB_len;i++) 87 { 88 getelem(LB,i,e);//取LB中第i个元素赋给e 89 if(!locateList(LA,e,equal)) 90 { 91 insertlist(LA,++LA_len,e);//LA中不存在和e相同的元素,则插入到LA中 92 } 93 } 94 } 95 96 int main() 97 { 98 SqList LA,LB ; 99 int i ,n,temp; 100 init_List(LA) ; 101 init_List(LB) ; 102 printf("输入集合A的数据个数:"); 103 scanf("%d",&n) ; 104 printf("输入集合A的所有数据(空格隔开):"); 105 for(i=1;i<=n;i++) 106 { 107 scanf("%d",&temp); 108 insertlist(LA,LA.length+1,temp) ; 109 } 110 111 printf("输入集合B的数据个数:"); 112 scanf("%d",&n) ; 113 printf("输入集合B的所有数据(空格隔开):"); 114 for(i=1;i<=n;i++) 115 { 116 scanf("%d",&temp); 117 insertlist(LB,LB.length+1,temp) ; 118 } 119 unionlist(LA,LB); 120 traveList(LA); 121 system("pause"); 122 return 0; 123 }
定义顺序表类型,写出向顺序表中某位置插入数据(insert),删除某位置数据(delete),显示所有数据(traversing),根据位置取元素(getelem),定位某数据(location)的算法,并实现集合A=AUB。
浙公网安备 33010602011771号