题目描述
给定一个链表,请判断该链表是否为回文结构。
输入描述:
n 表示链表的长度
ai 表示链表的各个节点的值。
输出描述:
如果为回文结构输出 “true” , 否则输出 “false”。
示例1
输入
4
1 2 2 1
输出
true
备注:
1≤n≤1000000
−1000000≤ai≤1000000
解法一:利用栈
import java.io.*;
import java.util.*;
public class Main{
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static ListNode creat() throws IOException{
int len = Integer.parseInt(br.readLine());
String[] ss = br.readLine().trim().split(" ");
ListNode head = new ListNode(0);
ListNode r = head;
for(int i=0;i<len;i++){
ListNode node = new ListNode(Integer.parseInt(ss[i]));
r.next = node;
r = node;
}
return head.next;
}
public static boolean judge(ListNode head){
Stack<Integer> stack = new Stack<>();
ListNode r = head;
while(r!=null){
stack.push(r.val);
r = r.next;
}
while(head!=null){
if(head.val!=stack.pop()) return false;
head = head.next;
}
return true;
}
public static void main(String[] args) throws IOException{
ListNode head = creat();
boolean result = judge(head);
System.out.println(result);
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val = val;
this.next = null;
}
}
解法二 优化一下只用一半栈
思路:ListNode r = head.next; ListNode tmp = head;r走一步,tmp走两步,最后r的位子为后半部分位置
public static boolean judge(ListNode head){
if(head==null||head.next==null) return true;
Stack<Integer> stack = new Stack<>();
ListNode r = head.next;
ListNode tmp = head;
while(tmp.next!=null&&tmp.next.next!=null){
r = r.next;
tmp = tmp.next.next;
}
while(r!=null){
stack.push(r.val);
r = r.next;
}
while(!stack.isEmpty()){
if(head.val!=stack.pop()) return false;
head = head.next;
}
return true;
}
解法三:反转链表的一半
思路: 注意走一步,走两步位置不同最后到的点不同!(对比上一题)
public static boolean judge(ListNode head){
if(head==null||head.next==null) return true;
ListNode n1 = head;
ListNode n2 = head;
while(n2.next!=null&&n2.next.next!=null){
n1 = n1.next; //中间节点
n2 = n2.next.next;
}
n2 = n1.next;
n1.next = null;
ListNode n3;
while(n2!=null){
n3 = n2.next;
n2.next = n1 ;
n1 = n2;
n2 = n3;
}
while(head!=null&&n1!=null){
if(head.val!=n1.val) return false;
head = head.next;
n1 = n1.next;
}
return true;
}