刷题笔记24——判断链表是否回文链表

文章目录

  • 题目描述
    • 解法1:使用栈
    • 解法2:快慢指针+栈
    • 测试代码


题目描述

给定一个链表的头节点head, 请判断该链表是否为回
文结构。 例如: 1->2->1, 返回true。 1->2->2->1, 返回true。15->6->15, 返回true。 1->2->3, 返回false。

解法1:使用栈

遍历链表,元素入栈,弹出时再从头判断即可
时间复杂度和额外空间复杂度都是O(N)
刷题笔记24——判断链表是否回文链表_第1张图片
刷题笔记24——判断链表是否回文链表_第2张图片

解法2:快慢指针+栈

利用快慢指针,快指针走两步,慢指针走一步
时间复杂度O(N),额外空间复杂度O(N/2)
刷题笔记24——判断链表是否回文链表_第3张图片
刷题笔记24——判断链表是否回文链表_第4张图片

测试代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    bool isPalindromeList1(ListNode* head) {
        if (head == NULL) 
            return false;
        if (head->next == NULL) // 只有一个结点,肯定是回文链表
            return true;

        ListNode *tmp = head;
        while (tmp != NULL) {
            stk.push(tmp->val);
            tmp = tmp->next;
        }
        while (!stk.empty()) {
            if (stk.top() == head->val) {
                stk.pop();
                head = head->next;
            }
            else
                return false;
        }
        return true;
    }

    bool isPalindromeList2(ListNode* head) {
        if (head == NULL)
            return false;
        if (head->next == NULL)
            return true;

        ListNode *quick = head;
        ListNode *slow = head;

        while (quick->next != NULL && quick->next->next != NULL) {
            quick = quick->next->next;
            slow = slow->next;
        }
        slow = slow->next;
        while (slow != NULL) {
            stk.push(slow->val);
            slow = slow->next;
        }
        while (!stk.empty()) {
            if (stk.top() == head->val) {
                stk.pop();
                head = head->next;
            } else {
                return false;
            }
        }
        return true;
    }

private:
    stack<int> stk;
};

void printNode(ListNode *head) {
    while (head != NULL) {
        cout << head->val << " ";
        head = head->next;
    }
    cout << endl;
}

int main(int argc, char *argv[])
{

    srand(time(NULL));
    const int test_time = 15; // 测试次数

    for (int cnt = 0; cnt < test_time; ++cnt) {
        int N = rand() % 10 + 1;
        cout << "第 " << cnt << " 次生成:" << N << "个数" << endl;
        ListNode *head = new ListNode(1);
        ListNode *tmp = head;

        for (int i = 1; i < N; ++i) {
            int value = rand() % 2 + 1;
            ListNode *cur = new ListNode(value);
            tmp->next = cur;
            tmp = cur;
        }
        printNode(head);
        
        Solution solution;
        if (solution.isPalindromeList1(head))
            cout << "-->方法1:Yes\n";
        else
            cout << "-->方法1:No\n";

        if (solution.isPalindromeList2(head))
            cout << "-->方法2:Yes\n";
        else
            cout << "-->方法2:No\n";

        cout << endl;
    }

    return 0;
}

你可能感兴趣的:(刷题)