链表问题7——判断一个链表是否为回文结构

题目

给定一个链表的头节点head,请判断该链表是否为回文结构。

输入链表 输出
1->2->1 true
1->2->2->1 true
15->6->15 true
1->2->3 false

思路

方法一:

利用栈结构,遍历链表并将节点依次压入栈中,遍历完后,依次弹栈,如果一个链表是回文结构,弹栈顺序对应的值和原链表顺序对应的值应该是一样的。

方法二:

类似方法一,不过不需要将节点全部压栈,仅仅将右半区压栈,并和链表左半部分比较。

举例:1->2->2->1,左半区:1->2;右半区: 2->1。 1->2->3->2->1,左半区:1->2;右半区:2->1.

 


源码

方法一:

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

public boolean isPanlindrome1(Node head){
	Stack<Node> stack=new Stack<Node>();
	Node cur=head;
	while(cur!=null){
		stack.push(cur);
		cur=cur.next;
	}
	while(head!=null){
		if(head.value!=stack.pop().value){
			return false;
		}
		head=head.next;
	}
	return true;
}

方法二:

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

public boolean isPanlindrome2(Node head){
	if(head==null||head.next==null){
		return true;
	}
	Node right=head.next;
	Node cur=head;
	while(cur.next!=null&&cur.next.next!=null){
		right=right.next;
		cur=cur.next;
	}
	Stack<Node> stack=new Stack<Node>();
	while(right!=null){
		stack.push(right);
		right=right.next;
	}
	while(!stack.isEmpty()){
		if(head.value!=stack.pop().value){
			return false;
		}
		head=head.next;
	}
	return true;
}
发布了43 篇原创文章 · 获赞 21 · 访问量 4914

猜你喜欢

转载自blog.csdn.net/flying_1314/article/details/103854022
今日推荐