import java.util.Stack;
public class pro {
public static void main(String[] args) {}
public static class Node { //单链表
public int value;
public Node next;
public Node(int data) { this.value = data; }
}
//方法一:使用栈
public static boolean isPalindrome1(Node head) {
Stack<Node> stack = new Stack<Node>();
Node cur = head; // cur指针赋予当前传入节点
while (cur != null) { //首节点置尾,每个节点依次压栈
stack.push(cur);
cur = cur.next;
}
while (head != null) { //依次比较,如果不同则返回false
if (head.value != stack.pop().value) {
return false;
}
head = head.next;
}
return true;
}
//方法二:还是使用栈,但是只用一半
public static boolean isPalindrome2(Node head) {
if (head == null ||
head.next == null) { //如果只有单节点或者没有节点都为回文链表
return true;
}
Node right = head.next, cur = head;
while (cur.next != null && cur.next.next != null) {
right = right.next; //慢指针
cur = cur.next.next; //快指针
}
Stack<Node> stack = new Stack<Node>(); //创建以Node为基本单位的栈
while (right.next != null) { //将慢指针后面的所有节点压栈
stack.push(right);
right = right.next;
}
while (!stack.isEmpty()) {
if (head.value != stack.pop().value) {
return false;
}
head = head.next;
}
return true;
}
//第三种方法:只用常数级别的额外空间
public static boolean isPalindrome3(Node head) {
if (head == null || head.next == null)
return true;
Node n1 = head, n2 = head;
while (n2.next != null && n2.next.next != null) {
n1 = n1.next; //慢指针走到一半
n2 = n2.next.next; //快指针走到末尾
}
n2 = n1.next; // n2变成后一半的第一个
n1.next = null; //阻断前一半
Node n3 = null;
while (n2 != null) { //逆转右边链表
n3 = n2.next;
n2.next = n1;
n1 = n2;
n2 = n3;
}
n3 = n1;
n2 = head;
boolean res = true;
while (n1 != null && n2 != null) {
if (n1.value != n2.value) {
res = false;
break;
}
n1 = n1.next;
n2 = n2.next;
}
n1 = n3.next;
n3.next = null;
while (n1 != null) {
n2 = n1.next;
n1.next = n3;
n3 = n1;
n1 = n2;
}
return res;
}
}
判断链表是否为回文链表
最新推荐文章于 2022-06-27 22:53:16 发布