- 论坛徽章:
- 24
|
- #include <iostream>
- using namespace std;
- #define OK 0
- #define ERROR 1
- typedef struct LNode
- {
- int data;
- struct LNode * next;
- } LNode ,*LinkList;
- int InitList_L(LinkList& L)
- {
- L = new LNode;
- if (L==NULL) return ERROR;
- L->data = NULL;
- L->next = NULL;
- return OK;
- }
- int DestroyList_L(LinkList& L)
- {
- LinkList p;
- while (L)
- {
- p = L;
- L=L->next;
- delete p;
- }
- return OK;
- }
- int GetElem_L(LinkList L,int i,int &e)
- {
- LinkList p = L->next;
- int j = 1;
- while (p != NULL && j<i)
- {
- p = p->next;
- ++j;
- }
- if (p == NULL || j>i )
- return ERROR;
- else
- {
- e = p->data;
- return OK;
- }
- }
- int ListInsert_L(LinkList &L,int i,int e)
- {
- LinkList p = L;
- int j=0;
- while (p && j < i-1)
- {
- p=p->next;
- j++;
- }
- if (p==NULL || j>i-1)
- return ERROR;
- else
- {
- LinkList s = new LNode;
- s->data = e;
- s->next = p->next;
- p->next = s;
- return OK;
- }
- }
- int ListDelete_L(LinkList & L,int i,int &e)
- {
- LinkList p = L;
- int j = 0;
- while (p->next && j< i-1)
- {
- p = p->next;
- ++j;
- }
- if (p->next==NULL || j>i-1)
- return ERROR;
- else
- {
- LinkList s = p->next;
- p ->next = s->next;
- e = s->data;
- delete s;
- return OK;
- }
- }
- void MergeList(LinkList & La,LinkList & Lb,LinkList & Lc)
- {
- LinkList pa,pb,pc;
- Lc = pc = La;
- pa = La->next;
- pb = Lb->next;
- while (pa && pb)
- {
- if (pa->data < pb ->data)
- {
- pc->next = pa;
- pc = pa;
- pa = pa->next;
- }
- else
- {
- pc->next = pb;
- pc = pb;
- pb = pb->next;
- }
- }
- pc->next = pa? pa:pb;
- delete Lb;
- }
- void ListPrint_L(LinkList L)
- {
- LinkList p = L->next;
- cout<<"LinkList:";
- while (p)
- {
- cout<<p->data<<",";
- p = p ->next;
- }
- cout<<endl;
- }
- int main(int argc, char* argv[])
- {
- LinkList L;
- InitList_L(L);
- ListPrint_L(L);
- ListInsert_L(L,1,1);
- ListInsert_L(L,2,5);
- ListInsert_L(L,3,8);
- ListInsert_L(L,4,10);
- ListPrint_L(L);
- int v;
- ListDelete_L(L,3,v);
- ListPrint_L(L);
- LinkList Lb;
- InitList_L(Lb);
- ListPrint_L(Lb);
- ListInsert_L(Lb,1,2);
- ListInsert_L(Lb,2,3);
- ListInsert_L(Lb,3,9);
- ListInsert_L(Lb,4,12);
- ListPrint_L(Lb);
- LinkList Lc;
- MergeList(L,Lb,Lc);
- ListPrint_L(Lc);
- return 0;
- }
复制代码 |
|