
链表反转后,如果直接使用原头节点进行遍历,可能会出现只打印一个节点的情况。这是因为反转后,原头节点变成了尾节点,其 next 指针指向 null,导致循环只执行一次。以下将详细介绍问题原因和几种解决方案。
问题分析
在提供的代码中,reverseList 函数会原地反转链表。这意味着反转后,原链表的头节点 head 实际上指向了反转后的链表的尾节点。由于尾节点的 next 指针为 null,因此在 isPalindrome 函数中使用 head 进行遍历时,循环只执行一次,仅打印第一个节点的值。
解决方案
以下提供三种解决方案,分别从空间复杂度和实现复杂度上进行考虑。
1. 创建新的反转链表
这种方法的核心思想是不修改原链表,而是创建一个新的链表,其节点顺序与原链表相反。这样,就可以同时遍历原链表和反转后的链表,进行比较。
class Solution { //Function to check whether the list is palindrome. boolean isPalindrome(Node head) { Node reversed = reverseList(head); // 创建反转后的新链表 Node cur = head; Node curReversed = reversed; while (cur != null && curReversed != null) { if (cur.data != curReversed.data) { return false; } cur = cur.next; curReversed = curReversed.next; } return true; } Node reverseList(Node head) { Node prev = null; Node current = head; Node next = null; Node newHead = null; // 新链表的头节点 while (current != null) { next = current.next; // 创建新节点并赋值 Node newNode = new Node(current.data); newNode.next = prev; prev = newNode; current = next; } newHead = prev; return newHead; }}
注意事项:
这种方法需要额外的 O(n) 空间来存储新的链表。需要修改 reverseList 函数,使其创建新的节点,而不是修改原链表节点的 next 指针。
2. 使用数组辅助判断
这种方法将链表中的所有节点值存储到一个数组中,然后判断该数组是否为回文数组。
import java.util.ArrayList;class Solution { //Function to check whether the list is palindrome. boolean isPalindrome(Node head) { ArrayList list = new ArrayList(); Node cur = head; while (cur != null) { list.add(cur.data); cur = cur.next; } int left = 0; int right = list.size() - 1; while (left < right) { if (!list.get(left).equals(list.get(right))) { return false; } left++; right--; } return true; }}
注意事项:
这种方法也需要额外的 O(n) 空间来存储数组。实现简单,易于理解。
3. 反转链表一半
这种方法只反转链表的前半部分,然后将反转后的前半部分与后半部分进行比较。这种方法可以在 O(1) 的空间复杂度下解决问题。
class Solution { //Function to check whether the list is palindrome. boolean isPalindrome(Node head) { if (head == null || head.next == null) { return true; } Node slow = head; Node fast = head; // Find the middle of the list while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // Reverse the second half of the list Node prev = null; Node current = slow; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } // Compare the first half and the reversed second half Node firstHalf = head; Node secondHalf = prev; while (secondHalf != null) { if (firstHalf.data != secondHalf.data) { return false; } firstHalf = firstHalf.next; secondHalf = secondHalf.next; } return true; }}
注意事项:
这种方法空间复杂度为 O(1),但实现相对复杂。需要找到链表的中间节点,并反转后半部分链表。如果链表长度为奇数,需要注意处理中间节点。
总结
本文分析了链表反转后只打印一个节点的问题,并提供了三种解决方案。选择哪种方案取决于具体的应用场景和对空间复杂度的要求。如果空间复杂度不是问题,可以使用创建新的反转链表或使用数组辅助判断的方法。如果对空间复杂度有严格要求,则需要使用反转链表一半的方法。 理解链表反转的原理以及各种解决方案的优缺点,可以帮助开发者更有效地解决相关问题。
以上就是解决链表反转后只打印一个节点的问题的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/49263.html
微信扫一扫
支付宝扫一扫