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

回文结构:

把中间作为起点,往左和往右的内容相同.

提供了三种解法:

1-额外空间复杂度为O(n) : 创建一个stack,将list中的数据遍历存到stack中,然后判断stack.pop.data是否等于list.next.value.

2-额外空间复杂度为O(n/2): 设置两个指针一个快一个慢,快指针一次走两步,慢指针一次走一步.当快指针不能往下走的时候,满指针到list中间.

将中间后边的部分存到栈里,和方法一 一样去判断.

3-额外空间复杂度为O(1),类似于方法2的办法找到list中间,找到之后,后半部分反转,变为类似于这样的结构1>2>3<4<5.然后两个指针一个指向head,一个指向end,遍历比较.

import java.util.Stack;

public class isPalindrome {
	public static void main(String[] args) {
		Node n1 = new Node(1);
		Node n2 = new Node(2);
		n1.next =n2;
		Node n3 = new Node(3);
		n2.next = n3;
		Node n4 = new Node(2);
		n3.next = n4;
		Node n5 = new Node(1);
		n4.next = n5;
		System.out.println(isPalindrome3(n1));
		
	}
	
	//need n extra space
	public static boolean isPalindrome1(Node head) {
		Stack<Node> stack = new Stack<Node>();
		
		Node cur = head;
		while(cur != null) {
			stack.add(cur);
			cur = cur.next;
		}
		cur = head;
		while(!stack.isEmpty()) {
			if(stack.pop().data != cur.data) {
				return false;
			}else {
				cur = cur.next;
			}
		}
		
		return true;
	}
	
	//need n/2 extra space
	public static boolean isPalindrome2(Node head) {
		Node f = head.next;
		Node s = head;
		
		while(f.next.next != null &&  s.next != null) {
			f = f.next.next;
			s = s.next;
		}
		
		Stack<Node> stack = new Stack<Node>();
		while(s != null) {
			stack.add(s.next);
			s = s.next;
		}
		f = head;
		while(!stack.isEmpty()) {
			if(stack.pop().data != f.data) {
				return  false;
			}else {
				f = f.next;
			}
		}
		return true;
	}
	
	//need O(1) extra space
	//按照方法2的办法找到list的中间节点,将后半部分的list反转.反转后一个指针从开头,另一个从中间逐个比较.
	public static boolean isPalindrome3(Node head) {

		Node n1 = head;
		Node n2 = head;
		while(n2.next != null && n2.next.next != null) {
			n1 = n1.next;
			n2 = n2.next.next;
		}//n1 is mid
		
		n2 = n1.next;
		n1.next = null;
		Node n3 = null;
		//right part convert
		while(n2 != null) {
			n3 = n2.next; //save next node
			n2.next = n1; //contact n2 to mid
			n1 = n2;
			n2 = n3;
		}
        //n3 > end 
		n3 = n1;
		n2 = head;
				
		while(n1 != null && n2 != null) {
			if(n1.data != n2.data) {
				return false;
			}else {
				n1 = n1.next;
				n2 = n2.next;
			}
		}
		
		return true;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_39445556/article/details/104824956