当前位置: 代码迷 >> 综合 >> 面试题 02.06. 回文链表(c++)
  详细解决方案

面试题 02.06. 回文链表(c++)

热度:15   发布时间:2024-03-07 16:46:45.0

编写一个函数,检查输入的链表是否是回文的。

 

示例 1:

输入: 1->2
输出: false 
示例 2:

输入: 1->2->2->1
输出: true 

 

分析:

栈法
根据逆序输出链表的思想,如果链表回文,则逆序输出和正序输出的序列应该相同
则可以用栈来辅助进行操作

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:bool isPalindrome(ListNode* head) {stack<int> temp;ListNode *p=head;     while (p!=NULL){temp.push(p->val);p=p->next;}ListNode *q=head;while(q!=NULL){if (q->val!=temp.top()){return false;}else{q=q->next;temp.pop();}}return true;}
};

 

  相关解决方案