标签:顺序表
顺序表的实现
我也是正在学链表,所以就按自己的想法把顺序表的基本实现功能写出来分享给大家, 希望对你有帮助。
1:头文件list.h
#ifndef _LIST_H_ #define _LIST_H_ #include<iostream.h> #include<stdlib.h> #define ElemType int #define error -1 typedef struct List { size_t size; ElemType data[]; }List; void Output(); void InitList(List *list);//初始化表 void PopList(List *list,ElemType x);//头插 void BackList(List *list,ElemType x); //尾插 void PopDelete(List *list); //头删 void BackDelete(List *list); //尾删 void DeleteList(List *list); //删除链表 int Find(List *list,ElemType x); //查找 void Sort(List *list); //排序 void InverseList(List *list);//翻转链表 void ShowList(List *list);//显示表 #endif2:功能实现部分list.cpp
#include"list.h" void Output() { cout<<"*******************************"<<endl; cout<<"* [1] PopList, [2] BackList *"<<endl; cout<<"* [3] ShowList, [4] PopDelete*"<<endl; cout<<"* [5] BackDelete [6] Find *"<<endl; cout<<"* [7] InverseList[8] Sort *"<<endl; cout<<"*******************************"<<endl; cout<<"请选择:"; } void InitList(List *list) { list->size=0; } void PopDelete(List *list) { for(int i=0;i<list->size;i++) { list->data[i]=list->data[i+1]; } list->size--; } void BackDelete(List *list) { list->size--; } void DeleteList(List *list) { list->size=0; } int Find(List *list,ElemType x) { for(int i=0;i<list->size;i++) { if(list->data[i]==x) return i; } return (error); } void Sort(List *list) { for(int i=0;i<list->size-1;i++) { for(int j=0;j<list->size-1-i;j++) { if(list->data[j]>list->data[j+1]) { int temp=list->data[j]; list->data[j]=list->data[j+1]; list->data[j+1]=temp; } } } } void InverseList(List *list) { int temp; int j=list->size-1; for(int i=0;i<list->size/2;i++,j--) { temp=list->data[i]; list->data[i]=list->data[j]; list->data[j]=temp; } } void PopList(List *list,ElemType x) { list->data[list->size]=x; list->size++; } void BackList(List *list,ElemType x) { for(int i=list->size;i>0;i--) { list->data[i]=list->data[i-1]; } list->data[0]=x; list->size++; } void ShowList(List *list) { for(int i=0;i<list->size;i++) { cout<<list->data[i]<<"-->"; } cout<<"OVER"<<endl; }3:主函数main.cpp
#include"list.h" void main() { List mylist; InitList(&mylist); int pos=1; int Number; while(pos) { Output(); cin>>pos; switch(pos) { case 1: cout<<"请输入数据,并以-1结束输入:"; while(cin>>Number,Number!=-1) { PopList(&mylist,Number); } break; case 2: cout<<"请输入数据,并以-1结束输入:"; while(cin>>Number,Number!=-1) { BackList(&mylist,Number); } break; case 3: ShowList(&mylist); break; case 4: PopDelete(&mylist); break; case 5: BackDelete(&mylist); break; case 6: cout<<"请输入值:"; cin>>Number; pos=Find(&mylist,Number); cout<<"寻找到的值:"<<mylist.data[pos]<<endl; break; case 7: InverseList(&mylist); break; case 8: Sort(&mylist); break; } } }注:这里的图片只显示一部分
标签:顺序表
原文地址:http://blog.csdn.net/zhou753099943/article/details/45342287