本文共 775 字,大约阅读时间需要 2 分钟。
判断一个单链表是否为回文链表的方法是,将链表中的所有节点值存储到一个数组中,然后从数组的两端同时向中间移动,逐步比较对应节点的值是否相等。如果全部相等,则为回文链表。
步骤如下:
代码示例:
bool isPalindrome(struct ListNode* head) { int n = 0; struct ListNode* current = head; // 计算链表长度 while (current != NULL) { n++; current = current->next; } int arr[n]; current = head; for (int i = 0; i < n; i++) { arr[i] = current->val; current = current->next; } int left = 0, right = n - 1; while (left < right) { if (arr[left] != arr[right]) { return false; } left++; right--; } return true;}
注意事项:该方法假设链表不为空。对于空链表,通常返回true。对于单节点链表,返回true。
转载地址:http://wfgfk.baihongyu.com/