[力扣c语言实现]234. 回文链表

234. 回文链表

1. 题目描述

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

示例 1:

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

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
题目链接

2.代码如下

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;
bool isPalindrome(struct ListNode* head){
    
    
    if (!head)
    {
    
    
        return false;
    }

    Node *pfast = head;
    Node *pslow = head;

    //先找到中间节点
    while (pfast->next && pfast->next->next)//通过快慢指针找到链表中间结点
    {
    
    
        pslow = pslow->next;
        pfast = pfast->next?pfast->next->next:pfast->next;
    }
    
    //逆转中间结点之后的结点以成为新链表
    Node *pnewlist = NULL;
    Node *ptmp = pslow->next;
    while (ptmp)
    {
    
    
        if (!pnewlist)
        {
    
    
            pnewlist = ptmp;
            ptmp = ptmp->next;
            pnewlist->next = NULL;
        }
        else
        {
    
    
            Node *p1 = ptmp;
            ptmp = ptmp->next;
            p1->next = pnewlist;
            pnewlist = p1;
        }
    }

    while (head && pnewlist)//变量比较两条链表是否一致
    {
    
    
        if (head->val != pnewlist->val)
        {
    
    
            return false;
        }

        head = head->next;
        pnewlist = pnewlist->next;
    }

    return true;
}

猜你喜欢

转载自blog.csdn.net/dengwodaer/article/details/115399906