题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
这道题的思路还是非常简单的,也没有什么坑点~
我才用的方法是比较笨的一种,首先,遍历一次链表得到链表的长度从而定义两个链表长度大小的数组来存储链表的内容,当然这需要又一次的遍历链表。
在将链表中的值存入数组后,我们通过比较两个数组的首尾并且以此类推,如果遇到不等的说明不是回文,如果前序遍历的index>=后续遍历的index说明是回文。
int getlen(struct ListNode* head)
{
int len = 0;
while(head!=NULL)
{
len++;
head = head->next;
}
return len;
}
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode* para_len = head;
int len = getlen(para_len);
int for_arr[len];
int back_arr[len];
for(int i=0;i<len;i++)
{
if(head!=NULL)
{
for_arr[i] = head->val;
back_arr[i] = head->val;
head = head->next;
}
else
{
printf("...error\n");
}
}
int pos_for = 0;
int pos_back = len-1;
while(1)
{
if(pos_for>=pos_back)
{
return true;
}
if(for_arr[pos_for]!=back_arr[pos_back])
{
return false;
}
else
{
pos_back--;
pos_for++;
}
}
}
阿里云工作强度 647人发布
