数据结构之两个线性表的合并
2011-08-30 17:22 javaspring 阅读(1080) 评论(0) 编辑 收藏 举报严蔚敏版的教材,算法2.2,下面是代码实现。。。。
#include <iostream> using namespace std; typedef int element; #define maxsize 100 typedef struct { element aa[maxsize]; int last; }sqlist; void mergelist(sqlist *la,sqlist *lb,sqlist *lc) { int i=0,j=0,k=0; while((i<=la->last)&&(j<=lb->last)) { if(la->aa[i]<=lb->aa[j]) { lc->aa[k]=la->aa[i]; i++; k++; } else { lc->aa[k]=lb->aa[j]; j++; k++; } } while(i<=la->last) { lc->aa[k]=la->aa[i]; i++; k++; } while(j<=lb->last) { lc->aa[k]=lb->aa[j]; j++; k++; } lc->last=la->last+lb->last+1; } int main() { int len,i; sqlist *la,*lb,*lc; la=(sqlist*)malloc(sizeof(sqlist)); cout<<"输入链表a的长度:"<<endl; cin>>len; la->last=len-1; cout<<"输入元素"<<endl; for(i=0;i<len;++i) cin>>la->aa[i]; lb=(sqlist*)malloc(sizeof(sqlist)); cout<<"输入链表b的长度:"<<endl; cin>>len; lb->last=len-1; cout<<"输入元素"<<endl; for(i=0;i<len;++i) cin>>lb->aa[i]; lc=(sqlist*)malloc(sizeof(sqlist)); mergelist(la,lb,lc); for(i=0;i<=lc->last;++i) cout<<lc->aa[i]<<" "; cout<<endl; return 0;
}