首页 > 其他 > 详细

检查链表是否为回文

时间:2015-08-19 13:27:44      阅读:137      评论:0      收藏:0      [点我收藏+]

技术分享编写一个函数,检查链表是否为回文。

技术分享

技术分享

#include<iostream>
#include<stack>
using namespace std;
typedef struct node
{
int data;
struct node* next;
}* LinkedListNode;
bool isPalindrome(LinkedListNode head)
{
LinkedListNode fast = head;
LinkedListNode slow = head;
stack<int> stack;
/*将链表前半部分元素入栈,当快速runner(
移动速度为慢速runner的两倍)到达链表尾部时,则
慢速runner已经处在链表中间位置*/
while (fast != NULL &&fast->next != NULL)
{
stack.push(slow->data);
slow = slow->next;
fast = fast->next->next;
}
/*链表有奇数个元素,跳过中间元素*/
if (fast != NULL)
{
slow = slow->next;
}
while (slow != NULL)
{
int top = stack.top();
stack.pop();
/*两者不相同,则该链表不是回文序列*/
if (top != slow->data)
{
return false;
}
slow = slow->next;
}
return true;
}

技术分享技术分享技术分享技术分享技术分享

Result isPalindromeRecurse(LinkedListNode head, int length)
{
if (head == null || length == 0)
{
return new Result(null, true);
}
else if (length == 1)
{
return new Result(head.next, true);
}
else
{
return new Result(head.next.next, head.data == head.next.data);
}
Result res = isPalindromeRecurse(head.next, length - 2);
if (!res.result || res.node = null)
return res;
else
{
res.result = head.data == res.node.data;
res.node = res.node.next;
return res;
}
}
boolean isPalindrome(LinkedListNode head)
{
Result p = isPalindromeRecurse(head, listSize(head));
return p.result;
}

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

检查链表是否为回文

原文:http://blog.csdn.net/wangfengfan1/article/details/47777245

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!