学习时间:
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】