左神算法笔记(六)——链表

链表操作详解

回文链表

  1. 创建一个栈,将链表中所有数据存入栈中,再将栈中数据与链表中的所有数据进行比较。
  2. 利用单步指针和双步指针,当双步指针最后到链表尾的时候,将后半部分链表指向取反,再从链表头和链表尾同时开始对比数据大小,实现回文链表的判断。空间复杂度为O(1)。
public static class Node{
   
   
	public int value ;
	public Node next;
	public Node(int data){
   
   
		this.value = data;
	}
}

//需要n个额外空间
public static boolean isPalinddrome1(Node head){
   
   
	Stack<Node> stack = new Stack<Node>();//建立一个node类型的栈
	Node cur = head;
	while(cur!=null){
   
   
		stack.push(cur);
		cur = cur.next;
	}
	while(head!= null){
   
   
		if(head.value != stack.pop().value){
   
   
			return false
		}
		head = head.next;
	}
	return true;
}


//需要n/2个额外空间
public static boolean isPalindrome2(Node node){
   
   
	//在只包含0个或1个数的时候,必定满足回文结构
	if(head == null ||head.next == null){
   
   
		return true;
	}
	//设置right为单步遍历,cur为双步遍历,因此需要提前将只包含0,1个数据的链表剔除,不然无法进行判断。
	Node right = head.next;
	Node cur = head;
	while(cur.next!=null &&cur.next.next !=null){
   
   
		right = right.next;
		cur = cur.next.next;
	}
	Stack<Node> stack = new Stack<Node>();
	while(right != null){
   
   
		stack.push(right);
		right = right.next;
	}
	while(!stack.isEmpty()){
   
   
		if(head.value != stack.pop().value){
   
   
			return false;
		}
		head = head.next;
	}
	return ture;
}

//需要O(1)额外空间
public static boolean isPalindrome3(Node head){
   
   
	if(head == null|| head.next == null){
   
   
		return ture;
	}
	Node n1 = head;
	Node n2 = head;
	while(n2.next !=null&&n2.next.next != null){
   
   
		n1 = n1.next;
		n2 = n2.next.next;
	}
	//n2变成了右半部分第一个点,将左右两边分开
	n2 = n1.next;
	n1.next = null;
	Node n3 = null;
	//通过while循环将右半部分的链表指向取反
	while(n2! = null){
   
   
		n3 = n2.next;
		n2.next = n1
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值