LeetCode234:回文链表

一、题目描述

    请判断一个链表是否为回文链表。
示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

/**
 * 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) {
    
    

    }
};

二、解题思路

    先判断链表长度

	int length=0;
    ListNode* p=head;
     while(p!=nullptr){
    
    
         length++;
         p=p->next;
     }

    创建一个与链表等长的数组,再把每个节点对应的值放入数组中

	int a[length];
    for(int i=0;i<length;i++){
    
    
        a[i]=p->val;
        p=p->next;
    }

    比较数组中对应的值

	for(int i=0;i<length/2;i++){
    
    
         if(a[i]!=a[length-i-1])
              return false;
        }

三、我的代码

    直接在力扣上写的。

/**
 * 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) {
    
    
        int length=0;
        ListNode* p=head;
        while(p!=nullptr){
    
    
            length++;
            p=p->next;
        }
        if(length==0||length==1)
            return true;
        p=head;
        int a[length];
        for(int i=0;i<length;i++){
    
    
            a[i]=p->val;
            p=p->next;
        }
        for(int i=0;i<length/2;i++){
    
    
            if(a[i]!=a[length-i-1])
                return false;
        }
        return true;
    }
};

四、测试结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45341339/article/details/111060183
今日推荐