每日一题 为了工作 2020 0322 第二十题

/**
* 问题: 判断一个链表是否为回文结构
* 给定一个链表的头节点head, 请判断该链表是否为回文结构。
*
* 例如:
* 1->2->1, 返回 true。
* 1->2->2-> 1, 返回 true 。
* 15->6-> 15, 返回 true。
* 1->2->3, 返回 false。
*
* 解答:
* 利用栈结构即可。从左到右遍历链表, 遍历的过程中把每个节点依次压入栈中。
* 因为栈是先进后出的, 所以在遍历完成后, 从栈顶到栈底的节点值出现顺序会
* 与原链表从左到右的值出现顺序反过来。那么, 如果一个链表是回文结构,
* 逆序之后, 值出现的次序还是一样的, 如果不是回文结构, 顺序就肯定对不上。
*
* 例如:
* 链表 1->2->3->4, 从左到右依次压栈之后, 从栈顶到栈底的节点值顺序为 4, 3, 2, 1。
* 两者顺序对不上, 所以这个链表不是回文结构。
* 链表1->2->2->1从左到右依次压栈之后, 从栈顶到栈底的节点值顺序为 1, 2, 2, 1。
* 两者顺序一样, 所以这个链表是回文结构。
*
* 分析:
* 需要一个额外的栈结构, 并且需要把所有的节点都压入栈中, 所以这个额外的栈结构需要 O(N)的空间。
*
*
* @author 雪瞳
*
*/

public class Node {
	public int value;
	public Node next;
	public Node(int data){
		this.value=data;
	}
}

  

public class Palindrome {

	private Stack<Integer> stack = null;
	private int currentValue = 0;
	private Node currentNext = null;
	private int stackValue = 0;
	
	public boolean isPalindrome(Node head) {
		
		stack = new Stack<>();
		currentNext = head;
		//将链表内元素压入栈内 链表尾对应栈顶
		while(currentNext!=null) {
			currentValue = currentNext.value;
			stack.push(currentValue);
			currentNext = currentNext.next;
		}
		//判断
		while(!stack.isEmpty()) {
			stackValue = stack.peek();
			currentValue = head.value;
			if(stackValue == currentValue) {
				stack.pop();
				head=head.next;
			}else {
				return false;
			}
		}
		return true;	
	}
}

  

public class TestIsPalindrome {
    
    private static boolean tip;
    
    public static void main(String[] args) {
        Palindrome plre = new Palindrome();
        TestIsPalindrome test = new TestIsPalindrome();
        Node head = new Node(1);
        Node n1 = new Node(2);
        Node n2 = new Node(1);
        Node n3 = new Node(4);
        Node n4 = new Node(5);

        
        // 1 2 1
        head.next = n1;
        n1.next = n3;
        
        test.showNode(head);
        tip = plre.isPalindrome(head);
        test.tipPrint(tip);;
    }
    public void showNode(Node head) {
        System.out.println("链表内的元素如下所示...");
        while(head != null) {
            System.out.print(head.value+"\t");
            head = head.next;
        }
        System.out.println();
    }
    public void tipPrint(boolean tip) {
        if(tip) {
            System.out.println("该链表是回文型链表!");
        }else {
            System.out.println("该链表不是回文型链表!");
        }
    }
    
}

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12545589.html