
链表反转后,如果发现只能输出一个节点,通常是因为原链表的结构在反转过程中被修改,导致全历时提前终止。具体来说,反转链表的原始节点已经变成了尾节点,而尾节点是 next 指针指向 null。因此,如果直接使用原始节点进行遍历,循环将立即结束。
有以下解决方案可以解决这个问题:
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; // 返回新链表的头节点
}
}
注意事项:
- 创建新的节点,而不是直接修改原节点的指针。
2. 使用数组辅助判断
该方法将链表中的所有元素存储在数组中,然后判断数组是否为回文。
AI建筑知识问答
使用人工智能ChatGPT帮助您解决所有建筑问题
22
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(n) 存储数组的空间。
3. 反转链表的前半部分
这种方法只反转链表的前半部分,然后将反转后的前半部分与后半部分进行比较。
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 middle node
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half
Node prev = null;
Node current = slow;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
Node firstHalf = head;
Node secondHalf = prev; // prev is the head of the reversed second half
// Compare the first half and the reversed second half
while (secondHalf != null) {
if (firstHalf.data != secondHalf.data) {
return false;
}
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
return true;
}
}
注意事项:
- 链表的中间节点需要找到。
- 若链表长度为奇数,则不需要参与中间节点的比较。
总结
链表反转是一种常见的操作,但需要注意反转过程中对原链表结构的影响。可根据具体需要选择不同的解决方案,如创建新的反转链表,使用数组辅助判断,或仅反转链表的前半部分。在选择解决方案时,需要权衡空间的复杂性和时间的复杂性。选择哪种方法取决于具体的应用场景和性能要求。
以上是解决链表反转后只输出一个节点的问题的详细内容。请关注图灵教育的其他相关文章!
相关标签:
java node NULL 循环 指针
大家都在看:
如何在Java中使用Formater格式化输出? 如何在Java中构建Spring开发环境? Java如何实现自定义异常的国际化提示? 加载Classloader的Java中类核心概念 Map接口和Java常用实现入门