您的位置:首页 > 其它

链表之判断一个链表是否为回文结构(三)

2016-01-03 23:29 344 查看
package com.chenyu.zuo.linkedList;

import com.chenyu.zuo.linkedList.PrintCommonPart.Node;

/**
 *  题目:给定一个头结点,判断该链表是否回文结构  
 * 例如:  
 * 1->2->1 true  
 * 1->2->2->1 true  
 * 1->2->3 false  
 *思路:
 *我们只需要几个变量,额外空间复杂度为0(1),
 *可以在时间复杂度o(N)内完成所有的过程
 *改变链表的右半区的结构,使整个右半区反转,最后指向中间节点
 *比如1->2->3->2->1
 *变成如下结构
 *1->2->
 *             3->null
 *1->2->
 *
 *1->2->3->3->2->1
 *变成如下结构
 *1->2->       3->null
 *1->2->3->
 *然后从左边和右边分别移动,如果每移动一步每个节点的值都相等
 *那么就是回文结构,不然不是
 *最后结果不管怎么样,我们应该把链表恢复原来的样子
 */
public class IsPalindrome3 {
	public static  class Node{//内部类
	   	  public Node next;
	   	  public int value;
	   	  public Node(int value){
	   		  this.value=value;
	   	  }
	}
	public boolean isPalindrome(Node head){
 		  if(head==null || head.next == null){
 			  return true;
 		  }
 		  Node n1=head;
 		  Node n2=head;
 		  while(n2.next !=null && n2.next.next !=null){  //查找中间节点
 			  n1=n1.next;                                                          //中部
 			  n2=n2.next.next;                                                  //尾部
 		  }
 		  n2=n1.next;//得到右部分的第一个节点
 		  n1.next=null;//mid.next->null
 		  Node n3 = null;
 		  while(n2!=null){  //右部分反转
 			  n3=n2.next;       //n3->保持下一个节点
 			  n2.next=n1;       //下一个反转节点
 			  n1=n2;               //n1右移
 			  n2=n3;               //n2移动
 		  }
 		  n3=n1;                  //保持最后一个节点
 		  n2=head;              //左边第一个节点
 		  boolean result=true;
 		  while(n2 != null && n1 !=null){  //检查回文
 			  if(n1.value != n2.value){
 				  result=false;
 				  break;
 			  }
 			  n1=n1.next;
 			  n2=n2.next;
 		  }
 		  n1=n3.next;
 		  n3.next=null;  //记得设置为空
 		  while(n1!=null){//恢复列表
 			  n2=n1.next;
 			  n1.next=n3;
 			  n3=n1;
 			  n1=n2;
 		  }
 		  return result;
 	  }
	   	  public static void main(String[] args) {
	   		  
	   		  Node firstNode=new Node(1);
			  Node  firstNode1=new Node(2);
			  Node  firstNode2=new Node(3);
			  Node  firstNode3=new Node(2);
			  Node  firstNode4=new Node(1);
			  firstNode.next= firstNode1;
			  firstNode1.next= firstNode2;
			  firstNode2.next= firstNode3;
			  firstNode3.next= firstNode4;
			   
			  IsPalindrome3 is=new IsPalindrome3();
			  System.out.println(is.isPalindrome(firstNode));
		}
	}


运行结果:

true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: