判断链表是否是回文数

public class IsPanlindromeList {
public static class Node{
Node next ;
int value;
public Node(int value){
this.value = value;
}
}
//第一种方法,用了空间复杂度为n,将链表压入栈中,之后将链表和栈中的元素逐个比对。
public static boolean isPanlindromeList1(Node head){
if(head==null&&head.next==null){
return true;
}
Stack<Node> stack = new Stack<>();
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 static void printLinkedList(Node node) {
System.out.print("Linked List: ");
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}
System.out.println();
}
//第二种方法。先求出链表的中间值,之后把后面的数据压入栈中,接下来,进行弹出比对。
public static boolean isPanlindromeList2(Node head){
if(head==null||head.next==null){
return true;
}
Node pre = head;
Node cur = head;
while (cur.next!=null&&cur.next.next!=null){
pre = pre.next;
cur = cur.next.next;
}
Stack<Node> stack = new Stack<>();
while (pre.next!=null){
stack.push(pre.next);
pre.next =pre.next.next;
}
while (!stack.isEmpty()){
if (stack.pop().value!=head.value){
return false;
}
}
return true;
}

//第三种方法,不借助辅助空间判断是不是回文数。
//先找到中间的那个,让他的指针指向null。之后把后面的链表部分反转。接下来在从两端开始进行比较
//记得把两端的数据保存起来。之后复原链表。
public static boolean isPanlindromeList3(Node head){
if(head==null||head.next==null){
return true;
}
Node cur1 = head;
Node cur2 = head;
while (cur2.next!=null&&cur2.next.next!=null){
//这样既满足了链表为单数的情况。又满足了链表为双数的情况。
//当链表为双数时,链表的中心默认为中间两个数中偏左边的那个数。
cur1 = cur1.next;
cur2 = cur2.next.next;
}
Node cur3 = cur1.next;
cur1.next = null;
while (cur3!=null){
cur2 = cur3.next;
cur3.next = cur1;
cur1 = cur3;
cur3 = cur2;
}
cur2 = head;
cur3 = cur1;
boolean flag = true;
while (cur1!=null&&cur2!=null){
if(cur1.value!=cur2.value){
flag = false;
}
cur1 = cur1.next;
cur2 = cur2.next;
}

cur2 = cur3.next;
cur3.next = null;

while (cur1!=null){
cur1 = cur2.next;
cur2.next = cur3;
cur3 = cur2;
cur2 = cur1;
}
return flag;
}
public static void main(String[] args) {
Node node1 = new Node(2);
node1.next = new Node(3);
node1.next.next = new Node(3);
node1.next.next.next = new Node(2);
// System.out.print(isPanlindromeList1(node1));
// System.out.print(isPanlindromeList2(node1));
System.out.print(isPanlindromeList3(node1));

}

}
总结;三种方法。最后一种方法最好。

posted on 2018-07-31 20:53  刘文涛123  阅读(218)  评论(0编辑  收藏  举报

导航