回文
2016-05-18 18:30
302 查看
今天数据结构上机,内容是队列,栈的一些基本操作,输入字符串,并判断是否是回文,我以为回文就是字符串首位字母相等,擦,居然看错了了,回文是第i个字母和倒数第i个字母相等(比如abcba,abccba都是回文,),所以不得不重新编写下程序;
判断是否是回文。顺序栈比较简单,而链队列也只是稍微麻烦点了,这里用双链表比较合理,即节点有不仅有next指针,还有prior指针,依次从两边往中间遍历就好了
判断是否是回文。顺序栈比较简单,而链队列也只是稍微麻烦点了,这里用双链表比较合理,即节点有不仅有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; } }
相关文章推荐
- Content-Type对照表
- Hdu oj 1004 Let the Balloon Rise(map)
- jQuery中this与$(this)的区别实例
- JAVA实现的一个简单的死锁(附解释)
- [KD-TREE] BZOJ 2850 巧克力王国
- 踏破铁鞋无觅处,从AsyncTask学Android线程池
- 踏破铁鞋无觅处,从AsyncTask学Android线程池
- Android WebView重定向的网页无法goBack()的几个解决方案
- [KD-TREE] BZOJ 1941 [Sdoi2010]Hide and Seek
- HUD 2544 最短路
- NanUI for Winform发布,让Winform界面设计拥有无限可能
- View坐标分析汇总
- Android自定义AsyncTaskLoader的使用
- 布局控件与地图控件关联
- 网络编程
- 64. Minimum Path Sum
- 是谁占用了我们的带宽:流量实时监控
- 如何在excel每一行数据后面都加一个逗号
- 堆和堆排序
- childNodes和Children的区别