第四周项目二
来源:互联网 发布:剑网三重制版 知乎 编辑:程序博客网 时间:2024/05/16 12:25
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- list.cpp:
-
-
-
- #include <stdio.h>
- #include <malloc.h>
- #include "list.h"
- void initList(Linklist *&L)
- {
- L=(Linklist *)malloc(sizeof(Linklist));
- L->next=NULL;
- }
-
- bool ListInsert(Linklist *&L,int i,ElemType e)
- {
- int j=0;
-
- Linklist *p=L,*s;
-
- if(i<=0)
- {
- return false;
-
- }
-
- while(j<i-1 && p!=NULL)
- {
- j++;
-
- p=p->next;
- }
-
- if(p==NULL)
- {
- return false;
- }
-
- else
- {
-
- s=(Linklist *)malloc(sizeof(Linklist));
-
- s->data=e;
-
- s->next=p->next;
-
- p->next=s;
-
- return true;
- }
- }
-
- 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 *pre=L,*p=L->next;
-
- while(p!=NULL)
- {
- free(pre);
-
- pre=p;
-
- p=pre->next;
- }
- free(pre);
- }
- void CreateListF(Linklist *&L,ElemType a[],int n)
- {
- Linklist *s;
-
- L=(Linklist *)malloc(sizeof(Linklist));
-
- L->next=NULL;
-
- for(int i=0;i<n;i++)
- {
- s=(Linklist *)malloc(sizeof(Linklist));
- s->data=a[i];
- s->next=L->next;
- L->next=s;
- }
- }
-
- void CreateListR(Linklist *&L,ElemType a[],int n)
- {
- Linklist *s,*r;
-
- L=(Linklist *)malloc(sizeof(Linklist));
-
- r=L;
-
- for(int i=0;i<n;i++)
- {
- s=(Linklist *)malloc(sizeof(Linklist));
-
- s->data=a[i];
-
- r->next=s;
-
- r=s;
-
- }
- r->next=NULL;
- }
-
-
-
- bool ListDelete(Linklist *&L,int i,ElemType &e)
- {
-
- int j=0;
-
- Linklist *p=L,*q;
-
- if(i<=0)return false;
-
- while(j<i-1 && p!=NULL)
- {
- j++;
-
- p=p->next;
- }
- if(p==NULL)
- {
- return false;
- }
-
- else
- {
- q=p->next;
- if(q==NULL)
- {
- return false;
- }
- e=q->data;
-
- p->next=q->next;
-
- free(q);
-
- return true;
- }
- }
-
-
-
- main:
-
- #include <stdio.h>
- #include <malloc.h>
- #include "list.h"
-
-
- int main()
- {
- Linklist *L1,*L2;
-
- ElemType a[8]={7,9,8,2,0,4,6,3};
-
- printf("头插法建表结果:");
-
- CreateListF(L1,a,8);
-
- DispList(L1);
-
- printf("尾插法建表结果:");
-
- CreateListR(L2,a,8);
-
- DispList(L2);
-
- DestoryList(L1);
-
- DestoryList(L2);
-
- int b;
-
- Linklist *L3;
-
- CreateListR(L3,a,8);
-
- ListDelete(L3,4,b);
-
- printf("删除a数组中的元素:");
- printf("%d\n",b);
- DispList(L3);
-
-
-
-
-
-
-
- printf("插入验证:");
- 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;
- }
-
- list.h:
-
- #include <stdio.h>
- #include <malloc.h>
- #include <stdio.h>
- #include <malloc.h>
- typedef int ElemType;
-
- typedef struct LNode
- {
- ElemType data;
-
- struct LNode *next;
- }Linklist;
- void initList(Linklist *&L);
- bool ListInsert(Linklist *&L,int i,ElemType e);
- void DispList(Linklist *L);
- void DestroyList(Linklist *&L);
- void CreateListF(Linklist *&L,ElemType a[],int n);
- void CreateListR(Linklist *&L,ElemType a[],int n);
- bool ListDelete(Linklist *&L,int i,ElemType &e);
运行结果: