线性表是数据结构最基础的东西,原先对于其使用方式一直处于懵懂状态,经过查找和学习,得到了其全面的基础应用,代码如下:
#include<iostream>
#include<cstdlib>
using namespace std;
#define maxsize 1000
typedef struct
{
int data[maxsize];
int last;
}ZgList;
typedef struct Node
{
int data;
struct Node *next;
}Node;
void CreateOrder(ZgList *L)
{
int n;
int i;
while(1)
{
cout<<"请输入顺序表长度:"<<endl;
cin>>n;
if(n>0)break;
else
{
cout<<"Error:顺序表的长度必须大于零!"<<endl;
}
}
cout<<"请输入顺序表元素:"<<endl;
L->last=n-1;
for(i=0;i<n;i++)
{
cin>>L->data[i];
}
}
void PrintOrder(ZgList *L)
{
int i;
if(L->last==-1)
{
cout<<"当前顺序表为空。"<<endl;
}
else
{
cout<<"当前顺序表为:"<<endl;
for(i=0;i<=L->last;i++)
{
cout<<L->data[i]<<" ";
}
cout<<endl;
}
}
void ReverseOrder(ZgList *L)
{
int i;
int j;
for(i=0,j=L->last;i<j;i++,j--)
{
L->data[i]^=L->data[j]^=L->data[i]^=L->data[j];//值互换
}
cout<<"顺序表逆置成功!"<<endl;
}
void PrintChain(Node *H)
{
cout<<"当前单链表为:"<<endl;
Node *p;
p=H->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//尾插法建单链表
void CreateChain(Node *H)
{
Node *s;
Node *p;//动态指向表尾
p=H;
int n;
int i;
H->next=NULL;//初始化,以确保重复建表的无误!!!!!
//输入N,并判断N是否合法
while(true)
{
cout<<"请输入单链表长度:";
cin>>n;
if(n>0)
{
break;
}
else
{
cout<<"Error:单链表的长度必须大于零!"<<endl;
}
}
cout<<"请输入单链表:"<<endl;
for(i=0;i<n;i++)
{
s=(Node *)malloc(sizeof(Node));
cin>>s->data;
s->next=p->next;
p->next=s;
p=p->next;
}
cout<<"成功创建新单链表!"<<endl;
PrintChain(H);
}
//利用顺序遍历同时用头插法重建单链表
void ReverseChain(Node *H)
{
Node *h;
Node *p;
Node *temp;
h=(Node *)malloc(sizeof(Node));
h->next=NULL;//初始化
p=H->next;
while(p!=NULL)
{
temp=p->next;
p->next=h->next;
h->next=p;
p=temp;//p=p->next
}
H->next=h->next;//将新表的头指针赋给原头指针(实现逆序)
cout<<"单链表逆置成功!"<<endl;
}
void Choose(int choice,ZgList *L,Node *H)
{
switch(choice)
{
case 4:
CreateOrder(L);break;
case 5:
PrintOrder(L);break;
case 6:
ReverseOrder(L);break;
case 1:
CreateChain(H);break;
case 2:
PrintChain(H);break;
case 3:
ReverseChain(H);break;
default:exit(0);
}
}
void Print(ZgList *L,Node *H)
{
int choice;
cout<<"1.建立新单链表"<<endl;
cout<<"2.打印当前单链表"<<endl;
cout<<"3.将单链表逆置"<<endl<<endl;
cout<<"4.建立新顺序表"<<endl;
cout<<"5.打印当前顺序表"<<endl;
cout<<"6.将顺序表逆置"<<endl<<endl;
cout<<"7.按其它任意键退出"<<endl;
cout<<"--------------------"<<endl;
cout<<"请选择你要的操作:";
cin>>choice;
Choose(choice,L,H);
}
int main(void)
{
ZgList L;
ZgList *p;
p=&L;
L.last=-1;//初始化
Node *H;
H=(Node *)malloc(sizeof(Node));
H->next=NULL;//初始化
Print(p,H);
while(true)
{
cout<<"按enter键继续...";
getchar();
getchar();
system("cls");
Print(p,H);
}
return 0;
}
代码多为借鉴,最重要是十分清晰,明了
线性表的应用
最新推荐文章于 2020-04-28 21:34:09 发布