第3周 实践项目2 建设”顺序表“算法库(可参考为模板)
生活随笔
收集整理的這篇文章主要介紹了
第3周 实践项目2 建设”顺序表“算法库(可参考为模板)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*
*Copyright (c) 2017,煙臺大學計算機與控制工程學院
*All rights reserved.
*文件名稱:項目2 -建設“順序表算法庫”
*作 者:邵雪源
*完成日期:2017年9月14日
*版 本 號:v1.0
*/ main.cpp
#include <stdio.h>
#include "list.h"
int main()
{SqList *sq;ElemType x[6]= {5,8,7,2,4,9};CreateList(sq, x, 6);DispList(sq);return 0;
}
list.h
#define LIST_H_INCLUDED#define MaxSize 50
typedef int ElemType;
typedef struct
{ElemType data[MaxSize];int length;
} SqList;
void CreateList(SqList *&L, ElemType a[], int n);//用數組創建線性表
void InitList(SqList *&L);//初始化線性表InitList(L)
void DestroyList(SqList *&L);//銷毀線性表DestroyList(L)
bool ListEmpty(SqList *L);//判定是否為空表ListEmpty(L)
int ListLength(SqList *L);//求線性表的長度ListLength(L)
void DispList(SqList *L);//輸出線性表DispList(L)
bool GetElem(SqList *L,int i,ElemType &e);//求某個數據元素值GetElem(L,i,e)
int LocateElem(SqList *L, ElemType e);//按元素值查找LocateElem(L,e)
bool ListInsert(SqList *&L,int i,ElemType e);//插入數據元素ListInsert(L,i,e)
bool ListDelete(SqList *&L,int i,ElemType &e);//刪除數據元素ListDelete(L,i,e)#endif // LIST_H_INCLUDED
#endif
list.cpp
#include <stdio.h>
#include <malloc.h>
#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;
}
//初始化線性表InitList(L)
void InitList(SqList *&L) //引用型指針
{L=(SqList *)malloc(sizeof(SqList));//分配存放線性表的空間L->length=0;
}//銷毀線性表DestroyList(L)
void DestroyList(SqList *&L)
{free(L);
}
//判定是否為空表ListEmpty(L)
bool ListEmpty(SqList *L)
{return(L->length==0);
}
//求線性表的長度ListLength(L)
int ListLength(SqList *L)
{return(L->length);
}
//輸出線性表DispList(L)
void DispList(SqList *L)
{int i;if (ListEmpty(L)) return;for (i=0; i<L->length; i++)printf("%d ",L->data[i]);printf("\n");
}
//求某個數據元素值GetElem(L,i,e)
bool GetElem(SqList *L,int i,ElemType &e)
{if (i<1 || i>L->length) return false;e=L->data[i-1];return true;
}
//按元素值查找LocateElem(L,e)
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;
}
//插入數據元素ListInsert(L,i,e)
bool ListInsert(SqList *&L,int i,ElemType e)
{int j;if (i<1 || i>L->length+1)return false; //參數錯誤時返回falsei--; //將順序表邏輯序號轉化為物理序號for (j=L->length; j>i; j--) //將data[i..n]元素后移一個位置L->data[j]=L->data[j-1];L->data[i]=e; //插入元素eL->length++; //順序表長度增1return true; //成功插入返回true
}
//刪除數據元素ListDelete(L,i,e)
bool ListDelete(SqList *&L,int i,ElemType &e)
{int j;if (i<1 || i>L->length) //參數錯誤時返回falsereturn false;i--; //將順序表邏輯序號轉化為物理序號e=L->data[i];for (j=i; j<L->length-1; j++) //將data[i..n-1]元素前移L->data[j]=L->data[j+1];L->length--; //順序表長度減1return true; //成功刪除返回true
}
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的第3周 实践项目2 建设”顺序表“算法库(可参考为模板)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第3周实践项目3 求集合并集
- 下一篇: 第3周实践项目4 -顺序表的应用 删除顺