三年前的大一暑假在家自學數據結構時寫的,各個方法見名知意。
#include<iostream>
#include<windows.h>
using namespace std;
typedef struct node
{
node *next;
int data;
}Node;
int count; //定義計數器
int i=0,j=0,k=0; //循環專用
Node *front; //設置隊頭指針
Node *tail; //設置隊尾指針
void init() //初始化隊列
{
front=new node; //front=(struct node*)malloc(sizeof(node));
front->next=NULL;
count=0;
tail=front;
}
bool empty()
{
if(count==0)
return true;
return false;
}
void insert()
{
system("cls");
int num;
cout<<"please input num:"<<endl;
cin>>num;
Node *p=new node;
p->data=num;
tail->next=p;
tail=tail->next;
count++;
cout<<"insert success!"<<endl;
}
void trave()
{
system("cls");
if(empty())
{
cout<<"empty queue!"<<endl;
return ;
}
else
{
cout<<"front-> ";
node *p=front->next;
while(p!=tail->next)
{
cout<<p->data;
if(p==tail)
{
cout<<" <-tail"<<endl;
}
else
{
cout<<" , ";
}
p=p->next;
}
}
}
void outqueue()
{
system("cls");
if(empty())
{
cout<<"empty queue!"<<endl;
return ;
}
Node *p1;
p1=front->next;
cout<<"隊頭元素爲:"<<p1->data<<endl;
front->next=p1->next;
delete p1;
count--;
}
void getlength()
{
system("cls");
cout<<"隊列長度爲:"<<count<<endl;
}
void destroy()
{
system("cls");
Node *p1,*p2;
p1=front->next;
while(p1!=tail)
{
p2=p1;
p1=p1->next;
delete p2;
}
front->next=NULL;//讓頭結點指向爲空 保證了安全性
tail=front;
cout<<"銷燬成功!"<<endl;
count=0;
}
void getfront()
{
system("cls");
cout<<"front="<<front->next->data<<endl;
}
void manushow_andchoice()
{
cout<<"1-----入隊\t2-----出隊"<<endl;
cout<<"3-----遍歷\t4-----銷燬隊"<<endl;
cout<<"5-----獲取隊頭元素\t6-----獲取隊列長度"<<endl;
cout<<"0-----退出"<<endl;
char choice;
while(choice!='0')
{
cin>>choice;
switch(choice)
{
case '1':insert();break;
case '2':outqueue();break;
case '3':trave();break;
case '4':destroy();break;
case '5':getfront();break;
case '6':getlength();break;
case '0':exit(0);
default:cout<<"error input!"<<endl;
}
cout<<"按回車鍵返回主菜單"<<endl;
getchar();
getchar();
system("cls");
manushow_andchoice();
}
}
int main()
{
SetConsoleTitle("鏈隊");//設置控制檯標題
init(); //初始化
manushow_andchoice(); //進入菜單選擇
return 0;
}