单链表归并问题
问题:实现链式存储结构上的归并有序表算法以下是我写的程序,在vs2008中编译没问题,但运行是发生了错误,请各位帮忙看看那里有问题
#include <iostream>
using namespace std;
enum status {
OK,
ERROR,
};
typedef struct Lnode {
double data;
Lnode *next;
} Lnode, *LinkList;
status CreatList( LinkList& L, int n ) { //建立单链表L,指定元素个数为n个
L = (LinkList)malloc(sizeof(Lnode));
L->next = NULL;
cout << "请输入元素:" << endl;
for( int i = 0; i < n; i++ ) {
Lnode *p = (LinkList)malloc(sizeof(Lnode));
cin >> p->data;
p->next = L->next;
L->next = p;
}
return OK;
}
status GetElem( LinkList L, int i, double &e ) { //取得L中的第i个元素并存储到e中
Lnode *p= L->next;
int j = 1;
while( p && j<i ) {
p = p->next;
++j;
}
if ( !p || j>i )
return ERROR; // 第i个元素不存在
e = p->data; // 取得第i个元素
return OK;
}
status ListInsert( LinkList& L, int i, double e ) //在L中的第i个位置插入元素e
{
Lnode *s = (LinkList)malloc(sizeof(Lnode));
s->data = e;
s->next = NULL;
Lnode *p = L;
int j = 0;
while( p && j < i-1 ) {
p = p->next;
++j;
}
if( !p || j > i-1 )
return ERROR;
s->next = p->next;
p->next = s;
return OK;
}
int LinkListLength(LinkList L) //取得L的长度
{
Lnode * p=L;
int j=0;
while (p->next) {
p=p->next;
j++;
}
return j;
}
void MergeList( LinkList LA, LinkList LB, LinkList &LC ) { //用归并算法:把LA和LB中的元素排序后存放到LC中
int i = 1, j = 1, k = 0;
double ai,bj;
int LA_len = LinkListLength(LA);
int LB_len = LinkListLength(LB);
while( ( i <= LA_len ) && ( j <= LB_len ) ) {
if( GetElem(LA,i,ai) <= GetElem(LB,j,bj) ) {
ListInsert(LC,k+1,GetElem(LA,i,ai));
k++;
i++;
}
else {
ListInsert(LC,k+1,GetElem(LB,j,bj));
k++;
j++;
}
}
while( i <= LA_len ) {
ListInsert(LC,k+1, GetElem(LA,i,ai));
k++;
i++;
}
while( j <= LB_len ) {
ListInsert(LC,k+1,GetElem(LB,j,bj));
k++;
j++;
}
}
int main()
{
int n;
LinkList LA, LB, LC;
cout << "请输入表1元素个数: ";
cin >> n;
CreatList( LA, n );
cout << "请输入表2元素个数:";
cin >> n;
CreatList( LB, n );
MergeList( LA, LB, LC );
n = LinkListLength(LC);
for( int i = n; i > 0; --i ) {
double val;
GetElem(LA,i,val);
cout << val << " ";
}
system("pause");
return 0;
}