方法一:
要判断一个链表是否为回文序列,可以采用以下步骤:
-
遍历链表,将链表中的元素逐个放入一个数据结构中,例如数组或列表,同时记录链表的长度。这个步骤可以使用迭代或递归来完成。
-
使用双指针技巧来比较链表中的元素是否对称。从头部和尾部同时向中间遍历,逐个比较对应位置的元素是否相等。如果在遍历过程中发现不相等的元素,就可以确定链表不是回文序列。
下面是一个Java示例代码,演示如何判断链表是否为回文序列。
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true; // 空链表或只有一个节点的链表视为回文
}
// 遍历链表,将元素放入数组中
int length = 0;
ListNode current = head;
while (current != null) {
length++;
current = current.next;
}
int[] elements = new int[length];
current = head;
for (int i = 0; i < length; i++) {
elements[i] = current.val;
current = current.next;
}
// 使用双指针比较元素是否对称
int left = 0;
int right = length - 1;
while (left < right) {
if (elements[left] != elements[right]) {
return false; // 如果元素不相等,链表不是回文
}
left++;
right--;
}
return true; // 如果所有元素对称相等,链表是回文
}
public static void main(String[] args) {
// 创建一个示例链表:1 -> 2 -> 2 -> 1
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(1);
PalindromeLinkedList solution = new PalindromeLinkedList();
boolean isPalindrome = solution.isPalindrome(head);
System.out.println("Is the linked list a palindrome? " + isPalindrome); // 输出:true
}
}
在上述代码中,我们首先遍历链表将元素放入数组中,然后使用双指针 left
和 right
来比较数组中的元素是否对称。如果所有元素对称相等,那么链表是回文序列。否则,不是回文序列。
方法二:
使用快慢指针来找到链表的中点,然后将链表的后半部分反转,最后比较前半部分和反转后的后半部分是否相等。
下面是一个Java示例代码。
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true; // 空链表或只有一个节点的链表视为回文
}
// 使用快慢指针找到链表的中点
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 反转链表的后半部分
ListNode reversedHalf = reverseList(slow);
// 比较前半部分和反转后的后半部分
ListNode current = head;
while (reversedHalf != null) {
if (current.val != reversedHalf.val) {
return false; // 如果元素不相等,链表不是回文
}
current = current.next;
reversedHalf = reversedHalf.next;
}
return true; // 如果所有元素对称相等,链表是回文
}
// 反转链表的函数
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
public static void main(String[] args) {
// 创建一个示例链表:1 -> 2 -> 2 -> 1
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(1);
PalindromeLinkedList solution = new PalindromeLinkedList();
boolean isPalindrome = solution.isPalindrome(head);
System.out.println("Is the linked list a palindrome? " + isPalindrome); // 输出:true
}
}