您的位置:首页 > 其它

回文

2016-05-18 18:30 302 查看
今天数据结构上机,内容是队列,栈的一些基本操作,输入字符串,并判断是否是回文,我以为回文就是字符串首位字母相等,擦,居然看错了了,回文是第i个字母和倒数第i个字母相等(比如abcba,abccba都是回文,),所以不得不重新编写下程序;

判断是否是回文。顺序栈比较简单,而链队列也只是稍微麻烦点了,这里用双链表比较合理,即节点有不仅有next指针,还有prior指针,依次从两边往中间遍历就好了

# include<iostream>
# define Elem char
typedef struct lNode
{
Elem data;
struct lNode *next;
struct lNode *prior;
}Node;
typedef struct lQueue
{
Node *front;
Node *rear;
}seqQueue;
void InitialQueue(seqQueue *&q);
bool QueueEmpty(seqQueue *q);
void EnQueue(seqQueue *&q, Elem x);
void OutQueue(seqQueue *&q, Elem &x);
void QueueTop(seqQueue *q, Elem &x);
using namespace std;
int main()
{
seqQueue *q;
InitialQueue(q);
cout << "请输入一串字符串,按#键结束:";
Elem ch;
cin >> ch;
while (1)
{
if ('#' == ch)break;
EnQueue(q, ch);
cin >> ch;
}
int j = 1;
Node *i = q->front->next;
while (i != NULL)
{
cout << "第" << j << "个元素为" << i->data << endl;
i = i->next;
j++;
}
//============判断是否是回文=======================
Node *p1 = q->front->next;//p1指向第一个节点
Node *p2 = q->rear;       //p2指向最后一个节点
while (true)
{
if (p1->data != p2->data)//只要有一组不相等,就不是回文
{
cout << "该字符串不是回文" << endl;
break;
}

if (p1->next == p2 || p1 == p2)//这里是两种情况,比如abccba和abcba
{
cout << "该字符串是回文" << endl;
break;//如果p1,p2到了中间就退出
}
p1 = p1->next;
p2 = p2->prior;

}

system("pause");
return 0;
}
void InitialQueue(seqQueue *&q)
{
q = new seqQueue;  //空接点
Node *node = new Node;
node->next = NULL;
node->prior = NULL;
q->front = q->rear = node;
}
bool QueueEmpty(seqQueue *q)
{
if (q->front == q->rear)
return true;
else return false;
}
void EnQueue(seqQueue *&q, Elem x)
{
Node *u = new Node;
u->next = NULL;//别忘了置空
u->prior = q->rear;
u->data = x;
q->rear->next = u;
q->rear = u;
}
void OutQueue(seqQueue *&q, Elem &x)
{
if (QueueEmpty(q))
cout << "队空,不能出队" << endl;
else
{
Node *u = q->front->next;
x = q->front->next->data;
q->front->next = u->next;
u->next->prior = q->front;
delete u;
u = NULL;
}
}
void QueueTop(seqQueue *q, Elem &x)
{
if (QueueEmpty(q))
cout << "队空,不能取队头元素" << endl;
else
{
x = q->front->next->data;
}
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: