检查链表是否为回文

来源:互联网 发布:淘宝旺旺买家 编辑:程序博客网 时间:2024/06/05 06:48

题目:编写一个函数,检查链表是否为回文。

解法一:根据回文的定义,正向反向读取时一致,即为回文,因此可以将原链表反转再与原链表比较,完全一样就是回文。算法比较简单就不贴代码了。

解法二:如果链表是回文,那么前半部分和后半部分一样,但是顺序相反。单链表没有前向指针,所以依靠指针只能在一个方向上比较。如果将链表的前半部分反序,就可以和后半部分比较了,反序可以用到数据结构栈。

bool IsPalindromicList(ListNode* pHead) {ListNode *fastPointer, *slowPointer;fastPointer = slowPointer = pHead;stack<ListNode*> s;while(fastPointer != NULL && fastPointer->m_pNext != NULL){s.push(slowPointer);slowPointer = slowPointer->m_pNext;fastPointer = fastPointer->m_pNext->m_pNext;}//奇数个结点,跳过中间结点if(fastPointer != NULL)slowPointer = slowPointer->m_pNext;while(slowPointer != NULL){if(slowPointer->m_nValue != s.top()->m_nValue)return false;slowPointer = slowPointer->m_pNext;s.pop();}return true;}


0 0