package practice;
import java.util.Stack;
/**
* 判断一个链表是否为回文结构【题目】 给定一个链表的头节点head,请判断该链表是否为回文结构。
* 例如: 1->2->1,返回true。 1->2->2->1,返回true。15->6->15,返回true。 1->2->3,返回false。
* 进阶: 如果链表长度为N,时间复杂度达到O(N),额外空间复杂度达到O(1)
* @author Colin
*
*/
public class IsReturnStru {
public static class Node{
int value;
Node next;
public Node(int data){
this.value=data;
}
}
static Stack<Node> halfDataStack=new Stack<Node>();
public static Node returnHalfNode(Node head){
Node lastNode=head;
while(head!=null){
halfDataStack.add(head);
lastNode=lastNode.next.next;
if(lastNode==null){
return head;
}
if(lastNode.next==null){
return head.next;
}
head=head.next;
}
return head;
}
public static Boolean isReturnStru(Node head){
Node halfNode = returnHalfNode(head);
while(!halfDataStack.isEmpty()){
if(halfDataStack.pop().value!=halfNode.next.value){
return false;
}
halfNode=halfNode.next;
}
return true;
}
public static void main(String[] args) {
Node head = new Node(0);
head.next= new Node(1);
head.next.next= new Node(2);
head.next.next.next= new Node(1);
head.next.next.next.next= new Node(1);
System.out.println(returnHalfNode(head).value);
while(!halfDataStack.isEmpty()){
System.out.print(halfDataStack.pop().value+" ");
}
// Node head = new Node(0);
// head.next= new Node(1);
// head.next.next= new Node(1);
// head.next.next.next= new Node(0);
//
//
//
// System.out.println(returnHalfNode(head).value);
// while(!halfDataStack.isEmpty()){
// System.out.print(halfDataStack.pop().value+" ");
// }
System.out.println(isReturnStru(head));
}
}
判断链表是否是回文结构
猜你喜欢
转载自blog.csdn.net/qq_42667028/article/details/86762485
今日推荐
周排行