
链表反转后,如果直接使用原头节点进行遍历,可能会出现只打印一个节点的情况。这是因为反转后,原头节点变成了尾节点,其 next 指针指向 null,导致循环只执行一次。以下将详细介绍问题原因和几种解决方案。
在提供的代码中,reverseList 函数会原地反转链表。这意味着反转后,原链表的头节点 head 实际上指向了反转后的链表的尾节点。由于尾节点的 next 指针为 null,因此在 isPalindrome 函数中使用 head 进行遍历时,循环只执行一次,仅打印第一个节点的值。
以下提供三种解决方案,分别从空间复杂度和实现复杂度上进行考虑。
这种方法的核心思想是不修改原链表,而是创建一个新的链表,其节点顺序与原链表相反。这样,就可以同时遍历原链表和反转后的链表,进行比较。
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;
}
}注意事项:
这种方法将链表中的所有节点值存储到一个数组中,然后判断该数组是否为回文数组。
import java.util.ArrayList;
class Solution {
//Function to check whether the list is palindrome.
boolean isPalindrome(Node head) {
ArrayList<Integer> 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(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;
}
}注意事项:
本文分析了链表反转后只打印一个节点的问题,并提供了三种解决方案。选择哪种方案取决于具体的应用场景和对空间复杂度的要求。如果空间复杂度不是问题,可以使用创建新的反转链表或使用数组辅助判断的方法。如果对空间复杂度有严格要求,则需要使用反转链表一半的方法。 理解链表反转的原理以及各种解决方案的优缺点,可以帮助开发者更有效地解决相关问题。
以上就是解决链表反转后只打印一个节点的问题的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号