链表7

1、题目

Given a singly linked list, determine if it is a palindrome.

Follow up:

Could you do it in O(n) time and O(1) space?

2、解答:给定一个链表,判断它是否是回文链表。C++的做法是 借助一个栈来存储数据,而python的经典做法是 对列表进行反转

3、C++代码

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        stack<int> stk {};                //借助一个栈
        ListNode  *p_Node = head;
        
        while(p_Node){
            stk.push(p_Node->val);   //数据入栈
            p_Node = p_Node->next;      
        }
        
        while(head){
            if(head->val != stk.top())   //原来数据与栈顶数据进行比较
                return false;
            
            stk.pop();                    
            head = head->next;
        }
        return true;
    }
};

python 代码  超巧妙的解法

class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        values = []
        while head:
            values += [head.val]         //把链表的每个值存入列表
            head = head.next
            
        return values == values[::-1]   //把链表进行反转,然后比较

猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80204011