题目连接:
判断一个链表是否为回文结构_牛客题霸_牛客网 (nowcoder.com)
题目描述:
描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 0≤n≤105,链表中每个节点的值满足 ∣val∣≤107
题目解法:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
*BM13 判断一个链表是否为回文结构
描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 0≤n≤10^5
,链表中每个节点的值满足 |val| <= 10^7
*/
/**************************code*****************************************/
struct ListNode {
int val;
struct ListNode *next;
};
//使用模拟栈的方式,先遍历获得链表长度,然后malloc申请st,重新遍历把值装入st,在st中用索引来判断是否回文
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode *tmp;
int count = 0;
long *st;
tmp = head;
while(tmp){ //遍历获得链表长度
count++;
tmp = tmp->next;
}
st = (long *)malloc(sizeof(long)*(count+1)); //malloc申请st
tmp = head;
count = 0;
while(tmp){ //重新遍历把值装入st
st[count++]=tmp->val;
tmp = tmp->next;
}
count--;
for(int i=0; i<=count/2; i++){ //在st中用索引来判断是否回文
if(st[i] != st[count-i]){
free(st);
return false;
}
}
free(st);
return true;
}
/**************************end******************************************/
void buildList(struct ListNode* head, int * input, int n){
for(int i=0; i<n; i++){
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = input[i];
head = head->next;
head->next = NULL;
head->val = 0;
}
}
int main ()
{
int input1[]={1,3,2,4,5};
int input2[]={1,2,3,2,1};
struct ListNode LNa, LNb;
buildList(&LNa, input1, sizeof(input1)/sizeof(int));
buildList(&LNb, input2, sizeof(input2)/sizeof(int));
bool ret = isPail(&LNb);
printf("\r\nret: %d", ret);
return 0;
}