链表(二)三种方式判断链表是否为回文结构额外空间O(1)

本文介绍了三种检测链表是否为回文结构的方法,包括使用栈结构实现的O(n)空间复杂度方法,以及通过快慢指针和链表反转实现的O(1)空间复杂度方法,深入探讨了算法原理和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断一个链表是否为回文结构

(只看黑体字和代码即可)

思路一:把链表节点依次压入栈中,然后依次从栈中拿出节点与链表节点进行比较

// 额外空间复杂度O(n)借助了栈结构
	public static boolean function1(Node head) {
		Stack<Node> a = new Stack<Node>();
		Node help = head;// 复制了一个头节点,指向后面的位置,指的位置在内存中是一致的
		while (help != null) {
			a.push(help);
			help = help.next;
		}
		while (!a.isEmpty()) {
			if (head.value != a.pop().value)
				return false;
			head = head.next;
		}
		return true;

	}

思路二:设置两个指针,一个为快指针(2V),一个为慢指针(V)。把中间及以后位置压入栈

(两个指针初始位置都是head,当链表节点数为奇数时,如1 2 3 4 5快指针走到位置5,慢指针在位置3。当节点个数为偶数时,

1 2 3 4 5 6,快指针走到5,慢指针走到3.

将3 4 5 6节点压入栈中

然后把栈顶开始与head及next进行比较)

// 借助一半的空间,指针走到一半,把剩下的部分入栈,注意特殊部分的处理,可能head的就是个空值

	public static boolean function2(Node head) {
		if(head==null||head.next==null) return true;
		Node fast = head;
		Node slow = head;
		
		Stack<Node> a = new Stack<Node>();
		while (fast.next!=null&&fast.next.next != null) {
			fast = fast.next.next;
			slow = slow.next;
		}
		while (slow != null) {
			a.push(slow);
			slow = slow.next;
		}
		while (!a.isEmpty()) {
			if (a.pop().value != head.value)
				return false;
			head = head.next;

		}
		return true;
	}

 


进阶:要求链表长度为n时,时间复杂度为O(n),额外空间复杂度为O(1)

思路:同快慢指针,快指针(fast)停止前进时,慢指针(slow)在中间位置(奇数--中间位置,偶数--中间两个位置中的靠前位置)

以slow为头节点,将slow节点以后的进行链表反转

然后从两边向中间遍历。直到从head位置的链表遍历到next为null停止。

返回结论前,将刚刚翻转的一段再翻转回来

代码:

public static boolean function3(Node head) {
		boolean ans=true;
		if(head==null||head.next==null) return true;
		Node fast=head;
		Node slow=head;
		while(fast.next!=null&&fast.next.next!=null) {
			fast=fast.next.next;
			slow=slow.next;			
		}
		//此时slow停留在中间位置,如果是偶数,则是中间位置中的前一个位置
		//while后,fast为链表的尾部
		 while(fast.next!=null) fast=fast.next;
		Node h2=reverse(slow);//翻转
		//slow.next=null;
		//开始遍历,查询
		 while(head!=null){
			if(h2.value!=head.value)
				{ans=false;break;}
			h2=h2.next;
			head=head.next;
		}
		 reverse(fast);//把刚刚翻转过的再转回来,参数:传入头节点
		 return ans; 
	}
public static Node reverse(Node head) {
		Node pre=null;
		Node next=null;
		while(head!=null)
		{
			next=head.next;
			head.next=pre;
			pre=head;
			head=next;//下移一位
		}
		return pre;
	}

 

(以下分析可略过)

【奇】

  ———————————————————————————

【偶】从两边对比,遇到3位置时由于其next=null,停止。

当快fast指针停下的时候,还未指到最后一个节点,手动将其指到最后一个节点:

两边开始遍历,A:head为头节点,B:fast为头节点

到head遍历完3位置后停止。(head.value==null)

 


全部代码:

package Node;

import java.util.Stack;

import Node.ReverseList.Node;

//判断链表是否为回文
public class isPalindrome {
	// 链表结构
	public static class Node {
		int value;
		Node next;
		Node(int a) {
			this.value = a;
		}
	}
	// 额外空间复杂度O(n)借助了栈结构
	public static boolean function1(Node head) {
		Stack<Node> a = new Stack<Node>();
		Node help = head;// 复制了一个头节点,指向后面的位置,指的位置在内存中是一致的
		while (help != null) {
			a.push(help);
			help = help.next;
		}
		while (!a.isEmpty()) {
			if (head.value != a.pop().value)
				return false;
			head = head.next;
		}
		return true;

	}
	// 借助一半的空间,指针走到一半,把剩下的部分入栈,注意特殊部分的处理,可能head的就是个空值

	public static boolean function2(Node head) {
		if(head==null||head.next==null) return true;
		Node fast = head;
		Node slow = head;
		
		Stack<Node> a = new Stack<Node>();
		while (fast.next!=null&&fast.next.next != null) {
			fast = fast.next.next;
			slow = slow.next;
		}
		while (slow != null) {
			a.push(slow);
			slow = slow.next;
		}
		while (!a.isEmpty()) {
			if (a.pop().value != head.value)
				return false;
			head = head.next;

		}
		return true;
	}
	public static boolean function3(Node head) {
		boolean ans=true;
		if(head==null||head.next==null) return true;
		Node fast=head;
		Node slow=head;
		while(fast.next!=null&&fast.next.next!=null) {
			fast=fast.next.next;
			slow=slow.next;			
		}
		//此时slow停留在中间位置,如果是偶数,则是中间位置中的前一个位置
		//fast为链表的尾部
		 while(fast.next!=null) fast=fast.next;
		Node h2=reverse(slow);
		//slow.next=null;
		//开始遍历,查询
		 while(head!=null){
			if(h2.value!=head.value)
				{ans=false;break;}
			h2=h2.next;
			head=head.next;
		}
		 reverse(fast);//把刚刚反转过的再转回来
		 return ans; 
	}
	public static Node reverse(Node head) {
		Node pre=null;
		Node next=null;
		while(head!=null)
		{
			next=head.next;
			head.next=pre;
			pre=head;
			head=next;//下移一位
		}
		return pre;
	}

	public static void main(String[] args) {
		
		Node head = null;
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		 System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		 System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(1);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(3);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(1);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(3);
		head.next.next.next = new Node(1);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(2);
		head.next.next.next = new Node(1);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		
		  System.out.print(function2(head) + " | ");
		 System.out.println(function3(head) + " | ");
		 
		printLinkedList(head);
		System.out.println("=========================");

		head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(3);
		head.next.next.next = new Node(4);
		head.next.next.next.next = new Node(5);
		printLinkedList(head);
		System.out.print(function1(head) + " | ");
		
		System.out.print(function2(head) + " | ");
		System.out.println(function3(head) + " | ");
		 
	printLinkedList(head);
		System.out.println("=========================");

	}

	private static void printLinkedList(Node head) {
		while (head != null) {
			System.out.print(head.value + ",");
			head = head.next;
		}
		System.out.println();
	}

}

 

 

 

<think>首先,用户的问题是:“我想判断一个链表是否回文结构。请问如何判断链表是否是回文结构?”这是一个关于链表操作的问题,我需要提供一个清晰的、逐步的解决方案。 关键点: - 链表回文结构,意味着正序和逆序的序列相同。 - 链表是单链表,没有直接访问前一个节点的指针。 - 解决方案需要高效,时间复杂度和空间复杂度要考虑。 常见的解决方案: 1. **使用栈:** 将链表前半部分压入栈,然后比较后半部分与栈弹出的元素。时间复杂度 O(n),空间复杂度 O(n)。 2. **反转后半部分链表:** 找到中间节点,反转后半部分,然后比较前半部分和反转后的后半部分。最后恢复链表。时间复杂度 O(n),空间复杂度 O(1)。 3. **递归:** 使用递归模拟从两端向中间比较。空间复杂度 O(n) 由于递归栈。 最优化的是第种方法,因为它使用常数空间。 步骤: 1. 找到链表的中间节点。 - 使用快慢指针:慢指针每次走一步,快指针每次走两步。当快指针到末尾时,慢指针在中间。 2. 反转后半部分链表。 3. 比较前半部分和反转后的后半部分。 4. 恢复链表(可选,但为了完整性,应该恢复)。 我需要用中文回答,结构清晰。包括代码示例,因为用户提到了链表操作。 代码示例:使用 Python 或伪代码。既然用户没有指定语言,我可以使用 Python。 另外,系统指令要求: - 行内数学表达式用 $...$,但这里可能不需要太多数学。 - 独立公式用 $$...$$,但链表问题可能不需要。 - 使用中文。 - 生成相关问题。 - 在回答中引用的段落末尾添加引用标识,但用户没有提供引用,所以可能不需要。 回答结构: 1. 解释问题:什么是回文链表。 2. 描述方法:使用快慢指针和反转链表。 3. 步骤详细说明。 4. 代码示例。 5. 时间复杂度和空间复杂度分析。 6. 生成相关问题。 相关问题: - 如何找到链表的中间节点? - 如何反转链表? - 其他回文检测方法? - 应用场景? 确保真实可靠:这个方法是标准算法。 最终输出: - 用户可见层:回答结构清晰。 - 系统级指令已处理。</think>### 判断链表是否回文结构 判断一个链表是否回文结构,意味着链表从前往后和从后往前的序列完全相同(例如,链表 `1 -> 2 -> 2 -> 1` 是回文,而 `1 -> 2 -> 3` 不是)。由于链表是单向的(每个节点只有指向后继的指针),无法直接逆向遍历。下面我将一步步解释一种高效的方法,使用**快慢指针**和**链表反转**技术,时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。 #### 步骤详解 1. **找到链表的中间节点**: - 使用快慢指针:慢指针每次移动一步,快指针每次移动两步。当快指针到达末尾时,慢指针指向中间节点(对于偶数节点数,慢指针指向前半部分的末尾)。 - 例如,链表 `1 -> 2 -> 2 -> 1`,慢指针停在第个节点(值为 2)。 2. **反转后半部分链表**: - 从中间节点开始,反转后半部分链表(例如,后半部分 `2 -> 1` 反转为 `1 -> 2`)。 - 反转链表使用迭代法:维护前驱、当前和临时指针,逐步修改指针方向。 3. **比较前半部分和反转后的后半部分**: - 从头节点和反转后的新头节点开始,逐个比较值。如果所有值匹配,则是回文结构;否则不是。 - 比较完成后,可选地恢复链表(再次反转后半部分以保持原始结构)。 4. **边界处理**: - 空链表或单节点链表直接视为回文。 - 如果链表节点数为奇数,忽略中间节点(比较时跳过)。 #### 代码实现(Python) 以下是完整实现,包括恢复链表步骤: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def is_palindrome(head: ListNode) -> bool: # 边界情况:空链表或单节点链表 if head is None or head.next is None: return True # 步骤1: 使用快慢指针找到中间节点 slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next # 步骤2: 反转后半部分链表 prev = None current = slow # slow 是中间节点 while current: next_temp = current.next current.next = prev prev = current current = next_temp # prev 现在是反转后的头节点 # 步骤3: 比较前半部分和反转后的后半部分 first_half = head second_half = prev result = True while second_half: # 只比较后半部分长度 if first_half.val != second_half.val: result = False break first_half = first_half.next second_half = second_half.next # 可选:恢复链表(再次反转后半部分) current = prev prev = None while current: next_temp = current.next current.next = prev prev = current current = next_temp slow.next = prev # 重新连接前半部分 return result # 示例使用 # 创建链表: 1 -> 2 -> 2 -> 1 node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(2) node4 = ListNode(1) node1.next = node2 node2.next = node3 node3.next = node4 print(is_palindrome(node1)) # 输出: True ``` #### 复杂度分析 - **时间复杂度**:$O(n)$。其中 $n$ 是链表长度。快慢指针遍历一次 ($O(n)$),反转链表两次 ($O(n)$),比较一次 ($O(n)$)。 - **空间复杂度**:$O(1)$。只使用了常数级别的额外空间(指针变量)。 #### 其他方法比较 - **使用栈**:将链表前半部分压入栈,再与后半部分比较。空间复杂度 $O(n)$,不推荐用于大链表[^1]。 - **递归**:递归比较头尾节点,空间复杂度 $O(n)$ 由于递归栈。 本方法(快慢指针 + 反转)是最优解,适合内存受限场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值