首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

判断一个链表是否回文数,要求O(n)时间

2012-08-28 
判断一个链表是不是回文数,要求O(n)时间1. 使用2个指针,快慢指针各一个,每次快指针移动一个,慢指针移动2个

判断一个链表是不是回文数,要求O(n)时间

1. 使用2个指针,快慢指针各一个,每次快指针移动一个,慢指针移动2个。

2. 当快指针不为NULL时候,将慢指针push到栈中。

3. 当快指针等于NULL时候,说明链表前半部分已经被压入栈中。

4. 每次栈Top元素与当前慢指针元素比较,如果不相等则返回false。如果相等,则栈Pop,慢指针++。

5. 链表奇数或者偶数节点需要判断。


#include <iostream>#include <stack>struct node{int data;node* next;node(int eData, node* eNext){data = eData;next = eNext;}};bool isPanli(node* head){std::stack<node*> stk;node* slow = head;node* fast = head;bool flag = false;while (fast){stk.push(slow);slow = slow->next;fast = fast->next;if (fast){fast = fast->next;}elseflag = true;}if (flag)stk.pop();while (!stk.empty()){if (stk.top()->data == slow->data){stk.pop();slow = slow->next;}elsereturn false;}return true;};int main(){node* n5 = new node(1, NULL);node* n4 = new node(2, n5);node* n3 = new node(3, n4);//node* n2 = new node(3, n3);node* n1 = new node(2, n3);node* n0 = new node(1, n1);bool res = isPanli(n0);return 0;}


热点排行