题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
#include <stdbool.h>
#include <stdlib.h>
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode *p1;
p1 = head;
//获取链表中的元素
int len = 0;
while(p1)
{
len++;
p1 = p1->next;
}
int *result = (int*)malloc(sizeof(int) * len);
//用数组保存链表的全部元素
p1 = head;
int i = 0;
for(i=0;i<len;i++)
{
result[i] = p1->val;
p1 = p1->next;
}
int *int_p1 = result;//数组头指针
int *int_p2 = &result[len-1];//数组尾指针
for(i=0;i<len/2;i++)
{
if(*int_p1 != *int_p2)
{
return false;
}
int_p1++;
int_p2--;
}
return true;
}
思路:动态申请一个数组保存链表中的元素,然后再利用双指针判断数组中的数据是否符号回文数据的定义即可。
