您的位置:首页 > 其它

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

2016-01-03 02:00 477 查看
package com.zuo.linkedlist;

import java.util.Stack;

import com.zuo.linkedlist.Josephuskill2.Node;

/**
 * 题目:给定一个头结点,判断该链表是否回文结构
 * 例如:
 * 1->2->1 true
 * 1->2->2->1 true
 * 1->2->3 false
 *
 *思路一:
 *我们把链表的每个节点压入stack,利用后进先出的特点,然后比较每个节点的值是否相等
 */
public class IsPalindrome1 {
	 static class Node{
	        public int val;
	        public Node next;
	        public Node(int val){
	        	this.val=val;
	        }
	    }
	 public boolean isPalindrome1(Node head){
		 if(head==null){
			 return false;
		 }
		 Stack<Node> stack=new Stack<Node>();
		 Node cur=head;
		 while(cur!=null){//记住这个地方不是cur.next不然最后一个节点没有压入栈
			 stack.push(cur);
			 cur=cur.next;
		 }
		 while(head.next!=null){
			 if(head.val!=stack.pop().val){
				 return false;
			 }
			 head=head.next;
		 }
		 return true;
	 }
	 public static void main(String[] args) {
		    Node node0=new Node(0);
			Node node1=new Node(1);
			Node node2=new Node(2);
			Node node3=new Node(2);
			Node node4=new Node(1);
			Node node5=new Node(0);

			node0.next=node1;
			node1.next=node2;
			node2.next=node3;
			node3.next=node4;
			node4.next=node5;
			
			IsPalindrome1 ip=new IsPalindrome1();			
			System.out.println(ip.isPalindrome1(node0));
			
	}
}

运行结果:

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