【力扣(LeetCode)】【C/C++】【234.回文链表】

学习时间:

        2023年1月22日


题目描述:


 题解分享:

// 作     者 : 繁 华 倾 夏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>                             // 调用malloc函数

// 力扣(LeetCode):234. 回文链表

//Definition for singly-linked list.    定义单链表
struct ListNode {
    int val;
    struct ListNode *next;
};

// head:单链表的头结点
bool isPalindrome(struct ListNode* head) {
    int nums[100000];                           // 将链表中的数据存储数组中,然后再进行比较
    int n = 0;                                  // 切记数组长度要跟测试数据长度保持一致,否则测试不通过
    while (head != NULL) {                      // 如果头结点不为空,则遍历链表
        nums[n++] = head->val;                  // 将链表中的每个数据赋值到数组中
        head = head->next;                      // 遍历
    }
    int i = 0, j = n - 1;                       // 设定两个变量,分别指向数组头和数组尾
    for (i, j; i < j; i++, j--) {               // 分别从前往后和从后往前遍历
        if (nums[i] != nums[j]) {               // 如果有任意一次元素不相等,则返回false
            return false;
        }
    }
    return true;                                // 如果程序顺利运行则返回true
}


// 从尾部插入数据
void SListPushBack(struct ListNode** pphead, int x) {
    struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newnode->val = x;
    newnode->next = NULL;
    if (*pphead == NULL) {
        *pphead = newnode;
    }
    else {
        // 找到尾节点
        struct ListNode* tail = *pphead;
        while (tail->next != NULL) {
            tail = tail->next;
        }
        tail->next = newnode;
    }
}

// 打印链表
void SListPrint(struct ListNode* phead)
{
    struct ListNode* cur = phead;
    while (cur != NULL) {
        printf("%d->", cur->val);
        cur = cur->next;
    }
    printf("NULL\n");
}


// 测试用例
// 输入 head = [1, 2, 2, 1]
// 输出 true
int main() {
    struct ListNode* head= NULL;                   // 建立空链表
    SListPushBack(&head, 1);                       // 为链表插入数据
    SListPushBack(&head, 2);
    SListPushBack(&head, 2);
    SListPushBack(&head, 1);

    bool re=isPalindrome(head);

    printf("%d", re);
    return 0;
}

【繁华倾夏】【每日力扣题解分享】【Day8】


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值