【LeetCode】234. 回文链表

请判断一个链表是否为回文链表。

解题思路:根据 O(n) 时间复杂度和 O(1) 空间复杂度的要求,则不能使用堆栈。首先找到中间节点,然后反转中间节点之后的节点,最后比较头结点和中间节点之后元素的大小。

bool Solution::isPalindrome(ListNode* head)
{
    if((head == NULL) || (head->next == NULL))
    {
        return true;
    }
    
    /*1.找到链表的中间位置*/
    ListNode *pslow, *pfast;
    pslow = pfast = head;
    while((pfast->next != NULL) && (pfast->next->next != NULL))
    {
        pslow = pslow->next;
        pfast = pfast->next->next;
    }
    /*2.目前pslow指向中间节点的前一个节点,从中间节点开始反转链表*/
    ListNode *Reversehead = pslow;
    ListNode *newprehead = NULL;
    ListNode *pcurrent = pslow->next;
    while(pcurrent != NULL)
    {
        ListNode *ptemp = pcurrent->next;
        pcurrent->next = newprehead;
        newprehead = pcurrent;
        pcurrent = ptemp;
    }
    Reversehead->next = newprehead;
    /*3.比较head和newprehead指向的数据*/
    while((head != NULL) && (newprehead != NULL))
    {
        if(head->val == newprehead->val)
        {
            newprehead = newprehead->next;
            head = head->next;
        }
        else
        {
            return false;
        }
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/syc233588377/article/details/85686190
今日推荐