【题目】
给定一个链表,请判断该链表是否为回文结构。
【输入】
n 表示链表的长度
ai 表示链表的各个节点的值。
【输出】
如果为回文结构输出 "true" , 否则输出 "false"。
【示例】
输入:4
1 2 2 1
输出:
true
【备注】
【解法1】
利用stack将整个链表入栈,然后出栈判断
public static boolean isPalindrome1(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;
}
【解法2】
利用stack入一半的栈(快慢指针),然后出栈与另一半判断
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
Node root = null;
Node temp = root;
for(int i=0; i<num; i++){
int val = sc.nextInt();
Node node = new Node(val);
if(temp != null){
temp.next = node;
}else{
temp = node;
root = node;
}
temp = node;
}
System.out.println(check(root,num));
}
public static boolean check(Node root,int sum){
Node temp = root;
Stack<Node> s = new Stack<>();
int i=0;
for(; i<sum/2; i++){
s.push(temp);
temp = temp.next;
}
temp = sum%2==0 ? temp :temp.next;
while(!s.isEmpty()){
Node tmp = s.pop();
if(temp.val!=tmp.val){
return false;
}
temp = temp.next;
}
return temp == null;
}
}
class Node{
public int val;
public Node next;
Node(int val){
this.val=val;
}
}