【初阶数据结构题目】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;
    }
};
相关推荐
tanyongxi6619 分钟前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
闪电麦坤952 小时前
数据结构:在二叉搜索树中插入元素(Insert in a BST)
数据结构·二叉树··二叉搜索树
闪电麦坤952 小时前
数据结构:用链式队列实现层序遍历 (Level-order Traversal)
数据结构··遍历
星星火柴93612 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑13 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
闪电麦坤9514 小时前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
Cx330❀14 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
散11214 小时前
01数据结构-Prim算法
数据结构·算法·图论
阿巴~阿巴~15 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
..过云雨15 小时前
01.【数据结构-C语言】数据结构概念&算法效率(时间复杂度和空间复杂度)
c语言·数据结构·笔记·学习