第三周项目4(2)
来源:互联网 发布:我的世界手机版火车js 编辑:程序博客网 时间:2024/06/03 12:48
问题及代码:
头文件list.h:- #define MaxSize 50
- #include <stdio.h>
- #include <malloc.h>
- typedef int ElemType;
- typedef struct
- {
- ElemType data[MaxSize];
- int length;
- } SqList;
- void CreateList(SqList *&L, ElemType a[], int n);
- void InitList(SqList *&L);
- void DestroyList(SqList *&L);
- bool ListEmpty(SqList *L);
- int ListLength(SqList *L);
- void DispList(SqList *L);
- bool GetElem(SqList *L,int i,ElemType &e);
- int LocateElem(SqList *L, ElemType e);
- bool ListInsert(SqList *&L,int i,ElemType e);
- bool ListDelete(SqList *&L,int i,ElemType &e);
源文件list.cpp:- #include "list.h"
-
-
-
- void CreateList(SqList *&L, ElemType a[], int n)
- {
- int i;
- L=(SqList *)malloc(sizeof(SqList));
- for (i=0; i<n; i++)
- L->data[i]=a[i];
- L->length=n;
- }
-
- void InitList(SqList *&L)
- {
- L=(SqList *)malloc(sizeof(SqList));
-
- L->length=0;
- }
-
- void DestroyList(SqList *&L)
- {
- L=(SqList *)malloc(sizeof(SqList));
- free(L);
- }
-
- bool ListEmpty(SqList *L)
- {
- return(L->length==0);
- }
-
- int ListLength(SqList *L)
- {
- return(L->length);
- }
-
- void DispList(SqList *L)
- {
- int i;
- if (ListEmpty(L)) return;
- for (i=0; i<L->length; i++)
- printf("%d ",L->data[i]);
- printf("\n");
- }
-
- bool GetElem(SqList *L,int i,ElemType &e)
- {
- if (i<1 || i>L->length) return false;
- e=L->data[i-1];
- return true;
- }
-
- int LocateElem(SqList *L, ElemType e)
- {
- int i=0;
- while (i<L->length && L->data[i]!=e) i++;
- if (i>=L->length) return 0;
- else return i+1;
- }
-
- bool ListInsert(SqList *&L,int i,ElemType e)
- {
- int j;
- if (i<1 || i>L->length+1)
- return false;
- i--;
- for (j=L->length; j>i; j--)
- L->data[j]=L->data[j-1];
- L->data[i]=e;
- L->length++;
- return true;
- }
-
- bool ListDelete(SqList *&L,int i,ElemType &e)
- {
- int j;
- if (i<1 || i>L->length)
- return false;
- i--;
- e=L->data[i];
- for (j=i; j<L->length-1; j++)
- L->data[j]=L->data[j+1];
- L->length--;
- return true;
- }
源文件main.cpp:- #include "list.h"
- #include <stdio.h>
-
-
- void move(SqList *&L)
- {
- int i=0,j=L->length-1;
- ElemType tmp;
- while (i<j)
- {
- while ((i<j) && (L->data[j]%2==0))
- j--;
- while ((i<j) && (L->data[i]%2==1))
- i++;
- if (i<j)
- {
- tmp=L->data[i];
- L->data[i]=L->data[j];
- L->data[j]=tmp;
- }
- }
- }
-
-
-
- int main()
- {
- SqList *sq;
- ElemType a[10]= {5,8,7,0,2,4,9,6,7,3};
- CreateList(sq, a, 10);
- printf("操作前 ");
- DispList(sq);
-
- move(sq);
-
- printf("操作后 ");
- DispList(sq);
- return 0;
- }
运行结果截图:
知识点总结:利用算法库可以帮助我们更好的理解程序
学习心得:要经常使用新的知识去解决问题,加强理解
0 0