第三周项目2 建设“顺序表”算法库

头文件LinkList.h

#include<stdio.h>  
#include<malloc.h>  
typedef int ElemType;  
typedef struct node  
{  
 int data;  
 node *next;  
  
}linklist;  
void InitList( linklist *& );  
void ListInsert(linklist *,int ,int );  
void DispList(linklist *);  
void DestroyList(linklist*);  
void CreateListF(linklist *&,ElemType a[],int );  
void CreateListF(linklist *&,ElemType a[],int ); 
源文件linklist.cpp:

#include"LinkList.h"  
void InitList(linklist *&l)  
{  
        l = (linklist*)malloc(sizeof(linklist));  
        l->next = NULL;  
}  
void ListInsert(linklist *l, int i, int e)  
{  
        linklist *p, *q;  
        int n = 0;  
        i--;  
        p = (linklist*)malloc(sizeof(linklist));  
        q = l;  
  
        while (l->next != NULL && n < i)  
        {  
                n++;  
                q = q->next;  
  
        }  
        if (l->next != NULL)  
        {  
  
                p->data = e;  
                p->next = q->next;  
                q->next = p;  
  
        }  
        if (l->next == NULL)  
        {  
                p->data = e;  
                p->next = l->next;  
                l->next = p;  
        }  
  
  
  
  
}  
void DispList(linklist *L)  
{  
        linklist *p = L->next;  
        while (p != NULL)  
        {  
                printf("%d ", p->data);  
                p = p->next;  
        }  
        printf("\n");  
}  
  
void DestroyList(linklist* l)  
{  
        linklist *q, *p;  
        int i = 0;  
        q = l;  
        p = l;  
        q = q->next;  
        while (q->next != NULL)  
        {  
                free(p);  
                p = q;  
                q = q->next;  
        }  
        free(q);  
}  
void CreateListF(linklist *&L, ElemType a[], int n)  
{  
        linklist *p;  
        int i = 0;  
        L = (linklist *)malloc(sizeof(linklist));  
        L->next = NULL;  
        while (i < n)  
        {  
                p = (linklist *)malloc(sizeof(linklist));  
                p->data = a[i];  
                p->next = L->next;  
                L->next = p;  
                i++;  
        }  
}  
  
  
void CreateListR(linklist *&L, ElemType a[], int n)  
{  
        linklist *p, *q;  
        int i = 0;  
  
        L = (linklist *)malloc(sizeof(linklist));  
        L->next = NULL;  
        q = L;  
        while (i < n)  
        {  
                p = (linklist *)malloc(sizeof(linklist));  
                p->data = a[i];  
                p->next = q->next;  
                q->next = p;  
                q = p;  
                i++;  
        }  
  
}  
main.cpp:

#include"LinkList.h"  
int main()  
{  
        linklist *L;  
        InitList(L);  
        ListInsert(L, 1, 15);  
        ListInsert(L, 1, 10);  
        ListInsert(L, 1, 5);  
        ListInsert(L, 1, 20);  
        DispList(L);  
        DestroyList(L);  
        return 0;  
}  





你可能感兴趣的:(第三周项目2 建设“顺序表”算法库)