LeetCode探索之旅(67)-234回文链表

今天继续刷LeetCode,第234题,判断一个链表是否是回文链表。

分析:
判断一个链表是否是回文,可以通过双指针法,一个慢一个快,找到中间位置,并且慢指针指向的数据进栈,再从中间开始往后遍历剩下的节点,并同时出栈,比较两者的值是否相等,以此判断是否是回文链表。
但是题目问是否可以不借用辅助空间,那么可以在找到中间位置后,选择链表反转,反转之后的剩下节点。然后再从头比较两者的值是否相等,这样就不会产生空间消耗。

问题:
1、指针的指向要小心;
2、反转链表的方式有很多,交换节点或者交换节点的值。

附上C++代码:

/**
 * 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||!head->next)
            return true;
        ListNode* slow=head,*fast=head;
        while(fast->next&&fast->next->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode * last=slow->next,*pre=head;
        while(last->next)
        {
            ListNode *temp=last->next;
            last->next=temp->next;
            temp->next=slow->next;
            slow->next=temp;
        }
        while(slow->next)
        {
            slow=slow->next;
            if(pre->val!=slow->val)
                return false;
            pre=pre->next;
        }
        return true;
    }
};

附上Python代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        fast=slow=head
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
        node=None
        while slow:
            tmp=slow.next
            slow.next=node
            node=slow
            slow=tmp
        while node:
            if node.val!=head.val:
                return False
            node=node.next
            head=head.next
        return True
    

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/88999636