Leetcode234-回文链表

题目

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

示例

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

code

思路:把链表的数据存入数组,然后用双指针一一比较。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 int get_len(ListNode* head){
     int len=0;
     while(head!=NULL){
         len++;
         head=head->next;
     }
     return len;
 }
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        int a[100000],i=0;
        for(ListNode*temp=head;temp!=NULL;temp=temp->next)
              a[i++]=temp->val;
        int num=get_len(head);
        for(i=0;i<num/2;i++)
            if(a[i]!=a[num-i-1]) return false;
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/Caiyii530/article/details/105750634
今日推荐