主题:[讨论]求助...这个简单问题却调了很久
要求:假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点,建立顺序链式存储循环队列,输入N个字符型数据,编写相应的队列入队和出队的算法,并显示该队列。
整个程序:
#include<stdio.h>
#include<iostream.h>
#define max 100
struct node{
char data;
node *next;
};
node *set()
{
node *head,*p,*s;
char ch[max];
head=new node;
p=head;
scanf("%s",&ch);
for(int i=0;ch[i]!='\0';i++)
{s=new node;s->data=ch[i];p->next=s;p=s;}
p->next=head;
return p;
}
void insert(node *p,char x)
{
node *s;
s=new node;
s->data=x;
s->next=p->next;
p->next=s;
p=s;
}
void del(node *p)
{
node *h,*t;
if(p->next==p) cout<<"队列为空"<<endl;
else {h=p->next;
t=h->next;
if(p==t) {p=h;p->next=p;}/*如果只有头节点和尾节点,就把尾指针指向头节点*/
else h->next=t->next;
cout<<t->data<<"已出队"<<endl;
delete t;}
}
void get(node *p)
{
if(p->next==p) cout<<"队列为空"<<endl;
else cout<<"队首元素为"<<p->next->next->data<<endl;
}
void display(node *p)
{
node *l;
if(p->next==p) cout<<"队列为空"<<endl;
else {l=p->next->next;
while(l!=p->next)
{cout<<l->data<<" ";l=l->next;}cout<<endl;}
}
void menu()
{
cout<<"1插入,2取队首,3出队,4显示"<<endl;
}
main()
{
int choice;
node *queue;
cout<<"建立队列:"<<endl;
queue=set();
while(1)
{
menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"输入要插入的数据:"<<endl;char x;cin>>x;insert(queue,x);break;
case 2:get(queue);break;
case 3:del(queue);break;
case 4:display(queue);
}
}
}
如上...插入一个元素后显示就有错误了.还有如果出队完了,判断队空的条件好像没用...请高手帮助...
整个程序:
#include<stdio.h>
#include<iostream.h>
#define max 100
struct node{
char data;
node *next;
};
node *set()
{
node *head,*p,*s;
char ch[max];
head=new node;
p=head;
scanf("%s",&ch);
for(int i=0;ch[i]!='\0';i++)
{s=new node;s->data=ch[i];p->next=s;p=s;}
p->next=head;
return p;
}
void insert(node *p,char x)
{
node *s;
s=new node;
s->data=x;
s->next=p->next;
p->next=s;
p=s;
}
void del(node *p)
{
node *h,*t;
if(p->next==p) cout<<"队列为空"<<endl;
else {h=p->next;
t=h->next;
if(p==t) {p=h;p->next=p;}/*如果只有头节点和尾节点,就把尾指针指向头节点*/
else h->next=t->next;
cout<<t->data<<"已出队"<<endl;
delete t;}
}
void get(node *p)
{
if(p->next==p) cout<<"队列为空"<<endl;
else cout<<"队首元素为"<<p->next->next->data<<endl;
}
void display(node *p)
{
node *l;
if(p->next==p) cout<<"队列为空"<<endl;
else {l=p->next->next;
while(l!=p->next)
{cout<<l->data<<" ";l=l->next;}cout<<endl;}
}
void menu()
{
cout<<"1插入,2取队首,3出队,4显示"<<endl;
}
main()
{
int choice;
node *queue;
cout<<"建立队列:"<<endl;
queue=set();
while(1)
{
menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"输入要插入的数据:"<<endl;char x;cin>>x;insert(queue,x);break;
case 2:get(queue);break;
case 3:del(queue);break;
case 4:display(queue);
}
}
}
如上...插入一个元素后显示就有错误了.还有如果出队完了,判断队空的条件好像没用...请高手帮助...