编写一个函数,检查链表是否为回文。
#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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。