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

本文介绍了一种判断链表是否为回文的方法。通过反转链表的后半部分并与前半部分进行对比,实现了高效地判断。文章提供了一个完整的Java实现案例。
public class IsHuiWenUpdate2 {

	public static boolean isHuiwenUpdate(Node head)
	{
		
		Node n1=head;
		Node n2=head;
		while(n2.next!=null&&n2.next.next!=null)
		{
			n1=n1.next;
			n2=n2.next.next;
		}
		
		n2=n1.next;
		Node pre=n1;
		Node next=null;
		while(n2!=null)
		{
			next=n2.next;
			n2.next=pre;
			pre=n2;
			n2=next;
		}
		n1.next=null;
			n2=pre;
			n1=head;
			while(n1.next!=null&&n2.next!=null)
			{
				if(n1.data!=n2.data)
					return false;
				n1=n1.next;
				n2=n2.next;
			}
			
			next=null;
			n2=null;
			while(pre!=null)
			{
				next=pre.next;
				pre.next=n2;
				n2=pre;
				pre=next;
			}
		
		return true;
	}
	
}
public class Test {

	public static void main(String[] args) {
	
	CreateQueue cq=new CreateQueue();
	boolean b=IsHuiWenUpdate2.isHuiwenUpdate(cq.a);
	
	System.out.println("链表是回文吗?"+b);
		
		}
}

public class CreateQueue {

	Node a=new Node(1);
	Node b=new Node(2);
	Node c=new Node(3);
	Node d=new Node(4);
	Node e=new Node(3);
	Node f=new Node(2);
	Node g=new Node(1);
	
	public CreateQueue()
	{
		a.next=b;
		b.next=c;
		c.next=d;
		d.next=e;
		e.next=f;
		f.next=g;
		g.next=null;
	}
}






                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值