题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
思路:创建一个反向链表,然后和已知的此链表同时遍历并比较值是否一样。如果是回文,那么这两个链表肯定完全相同
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
#include <stdlib.h>
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode* head_second = NULL;
struct ListNode* head_second_temp = NULL;
struct ListNode* head_temp = head;
int flag = 0;
while (NULL != head_temp) {
head_second_temp = (struct ListNode*)malloc(sizeof(struct ListNode));
if(NULL == head_second_temp)
{
printf("fxs error \r\n");
return false;
}
memcpy(head_second_temp, head_temp, sizeof(struct ListNode));
if (0 == flag) {
head_second = head_second_temp;
head_second_temp->next = NULL;
flag = 1;
} else {
//head_second_temp->next = head_second->next; 这个地方写了一个小bug调试了一会,惭愧。
head_second_temp->next = head_second;
head_second = head_second_temp;
}
head_temp = head_temp->next;
}
head_temp = head;
head_second_temp = head_second;
while(NULL != head_temp)
{
if(head_temp->val != head_second_temp->val)
{
return false;
}
head_temp = head_temp->next;
head_second_temp = head_second_temp->next;
}
return true;
}

