【初阶数据结构题目】10. 链表的回文结构

链表的回文结构

点击链接做题

思路1:创建新的数组,遍历原链表,遍历原链表,将链表节点中的值放入数组中,在数组中判断是否为回文结构。

例如:

排序前:1->2->2->1

设置数组来存储链表,设置数组头指针left和数组尾指针right

判断leftright指向的数是否相等,相等就left++;right--;,直到left > right

思路代码:

c 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        // write code here
        int arr[900] = {0};
        int i = 0;
        ListNode* pcur = A;
        //遍历链表,将链表中每个节点中的数值储存在数组中
        while(pcur){
            arr[i++] = pcur->val;
            pcur = pcur->next;
        }
        //i即结点的个数
        //找中间节点,判断是否为回文数字
        int left = 0;//数组头指针
        int right = i - 1;//数组尾指针
        while(left < right){
            if(arr[left] != arr[right]){
                //不是回文结构
                return false;
            }
            left++;
            right--;
        }
        //是回文结构
        return true;
    }
};

思路2:反转链表

  1. 找链表的中间节点(快慢指针)
  2. 将中间节点之后的链表进行反转
  3. 从原链表的头和反转链表比较节点的值
c 复制代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
    public:
    ListNode* findMidNode(ListNode* phead){
        ListNode* slow = phead;
        ListNode* fast = phead;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* reverseList(ListNode* phead){
        ListNode* n1, *n2, *n3;
        n1 = NULL; n2 = phead, n3 = n2->next;
        while(n2){
            n2->next = n1;
            n1 = n2;
            n2 = n3;
            if(n3){
                n3 = n3->next;
            }
        }
        return n1;
    }

    bool chkPalindrome(ListNode* A) {
        // write code here
        //1.找中间节点
        ListNode* mid = findMidNode(A);
        //2.根据中间节点反转后面链表
        ListNode* right = reverseList(mid);
        //3.从原链表的头和反转链表比较节点的值
        ListNode* left = A;

        while(right){
            if(left->val != right->val){
                return false;
            }
            left = left->next;
            right = right->next;
        }
        return true;
    }
};
相关推荐
yuuki2332333 小时前
【数据结构】用顺序表实现通讯录
c语言·数据结构·后端
还是码字踏实4 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
抠脚学代码8 小时前
Linux开发-->驱动开发-->字符设备驱动框架
linux·数据结构·驱动开发
星释11 小时前
Rust 练习册 8:链表实现与所有权管理
开发语言·链表·rust
熬了夜的程序员11 小时前
【LeetCode】101. 对称二叉树
算法·leetcode·链表·职场和发展·矩阵
橘颂TA12 小时前
【剑斩OFFER】算法的暴力美学——串联所有单词的字串
数据结构·算法·c/c++
葵续浅笑13 小时前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
Miraitowa_cheems13 小时前
LeetCode算法日记 - Day 94: 最长的斐波那契子序列的长度
java·数据结构·算法·leetcode·深度优先·动态规划
.ZGR.14 小时前
第十六届蓝桥杯省赛 C 组——Java题解1(链表知识点)
java·算法·链表·蓝桥杯
Paxon Zhang16 小时前
数据结构之**二叉树**超全秘籍宝典2
java·数据结构·算法