LeetCode 234
Palindrome Linked List
Problem Description:
判断链表是否是回文链表。所谓回文,即序列从两头起以相同速度向中间靠拢的过程中,对应位置的元素相同,比如1-2-2-1或者1-2-3-2-1都是回文序列。
具体的题目信息:
https://leetcode.com/problems/palindrome-linked-list/description/Solution:
总体思路是用栈实现。我们先扫描一遍链表记录链表长度,对于前半截链表中的元素我们push进第一个栈中,对于后半截链表需要借助一个temp中转栈,使得后半截链表的元素可以相当于从链表尾部开始push进第二个栈。其中有一个细节需要注意,即链表长度为单数时,当前链表指针需要比双数情况多执行一步p=p->next
,因为中间元素不影响回文序列的判断。
/**
* 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) {
if (head == NULL)
return true;
if (head->next == NULL)
return true;
stack<int> list1;
stack<int> temp;
stack<int> list2;
ListNode* p = head;
int count = 0;
while(p) {
p = p->next;
count++;
}
p = head;
int list1_count = 0;
int list2_count = 0;
while(p && list1_count != count/2) {
list1.push(p->val);
p = p->next;
list1_count++;
}
if (count%2) {
p = p->next;
}
while(p && list2_count != count/2) {
temp.push(p->val);
p = p->next;
list2_count++;
}
while(!temp.empty()) {
list2.push(temp.top());
temp.pop();
}
while(!list1.empty()) {
if (list1.top()!= list2.top())
return false;
list1.pop();
list2.pop();
}
return true;
}
};