首页 > 试题广场 >

判断一个链表是否为回文结构

[编程题]判断一个链表是否为回文结构
  • 热度指数:2566 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个链表,请判断该链表是否为回文结构。

输入描述:
n 表示链表的长度

ai 表示链表的各个节点的值。


输出描述:
如果为回文结构输出 "true" , 否则输出 "false"。
示例1

输入

4
1 2 2 1

输出

true

备注:

简单版本:先将链表的节点依次放入到栈中,然后在顺序遍历链表的同时一边弹栈比较
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;

class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] strList = br.readLine().trim().split(" ");
        ListNode head = new ListNode(Integer.parseInt(strList[0]));
        ListNode cur = head;
        for(int i = 1; i < n; i++){
            cur.next = new ListNode(Integer.parseInt(strList[i]));
            cur = cur.next;
        }
        System.out.println(isPalindrome(head));
    }
    
    private static boolean isPalindrome(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode cur = head;
        while(cur != null){
            stack.push(cur.val);
            cur = cur.next;
        }
        cur = head;
        while(cur != null){
            if(cur.val != stack.pop()) return false;
            cur = cur.next;
        }
        return true;
    }
}

发表于 2021-11-13 22:41:50 回复(0)
import java.io.*;
public class Main {
        public static void main(String[] args)throws IOException{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            br.readLine();
            String[] s=br.readLine().split(" ");
            int n=s.length;
            int mid=n/2;
            boolean res=true;
            for(int i=0;i<mid;i++){
                if(s[i].equals(s[s.length-1-i])){
                    
                }else{
                    res=false;
                    break;
                }
            }
            System.out.println(res);
        }
}

发表于 2021-03-09 11:14:43 回复(0)
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = scan.nextInt();
		}
		int L = 0;
		int R = arr.length -1;
		while(L < R) {
			if(arr[L] != arr[R]) {
				System.out.println(false);
				return;
			}
			L++;
			R--;
		}
		System.out.println(true);
	}
}

发表于 2019-09-06 21:46:22 回复(0)

问题信息

上传者:小小
难度:
4条回答 3622浏览

热门推荐

通过挑战的用户

查看代码