数据结构上机课,无聊。。。(严蔚敏那本书上的例题)
/*
Another: Von
Data: 2011/09/06
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
const int LIST_SIZE = 100;
const int LISTINCREMENT = 10;
struct sqlist
{
int * elem;
int len;
int listsize;
};
//creat
int InitList_sq(sqlist &l)
{
l.elem = (int *)malloc(LIST_SIZE*sizeof(int));
if(!l.elem) return 0;
l.len = 0;
l.listsize = LIST_SIZE;
return 1;
}
//insert 2.3
int Insert(sqlist &l, int i, int e)
{
if(i < 1 || i > l.len + 1) return 0;
if(l.len >= l.listsize)
{
int * newbase;
newbase = (int *)realloc(l.elem, (l.listsize + LISTINCREMENT)*sizeof(int));
if(!newbase) return 0;
l.elem = newbase;
l.listsize += LISTINCREMENT;
}
int * q, * p;
q = &(l.elem[i-1]);
for(p = &(l.elem[l.len - 1]); p >= q; --p)
*(p+1) = *p;
*q = e;
++l.len;
return 1;
}
//delete 2.4
int del(sqlist &l, int i, int e)
{
if(i < 1 || i > l.len) return 0;
int * p, * q;
p = &(l.elem[i-1]);
e = *p;
q = l.elem + l.len - 1;
for(++p; p <= q; ++p) *(p-1) = *p;
l.len--;
return 1;
}
//find 2.5
int Locate(sqlist &l, int e)
{
int i = 1;
int * p = l.elem;
while(i <= l.len && *p++ != e) ++i;
if(i <= l.len) return i;
return 0;
}
//merge 2.6
int Merge_list(sqlist la, sqlist lb, sqlist &lc)
{
int *pa, *pb, *pc;
pa = la.elem;
pb = lb.elem;
lc.listsize = lc.len = la.len + lb.len;
pc = lc.elem = (int *)malloc(lc.listsize*sizeof(int));
int *pa_last = la.elem + la.len - 1;
int *pb_last = lb.elem + lb.len - 1;
while(pa <= pa_last && pb <= pb_last)
{
if(*pa <= *pb) *pc++ = *pa++;
else *pc++ = *pb++;
}
while(pa <= pa_last) *pc++ = *pa++;
while(pb <= pb_last) *pc++ = *pb++;
return 1;
}
void print(sqlist &l)
{
int i;
for(i =0; i < l.len; i++)
{
cout << l.elem[i] << " ";
}
cout << endl;
}
//main function
int main()
{
int i, e;
sqlist l;
if(InitList_sq(l))
cout << "OK" << endl;
else
cout << "NO" << endl;
for(i = 1; i <= 5; i++)
{
cin >> e;
Insert(l, i, e);
}
print(l);
cout << "Please input the i-th number you want to delete :" << endl;
cin >> i;
del(l, i, e);
cout << e << endl;
print(l);
cout << "Please input the number you want to find :" << endl;
cin >> e;
cout << "It is the " << Locate(l, e) << "-th number!(0-th meams not find)"<< endl;
sqlist lb, lc;
InitList_sq(lb);
InitList_sq(lc);
cout << "Please input another array :" << endl;
for(i = 1; i <= 5; i++)
{
cin >> e;
Insert(lb, i, e);
}
Merge_list(l, lb, lc);
print(lc);
return 0;
}