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

【题目】

给定一个链表,请判断该链表是否为回文结构。

【输入】

 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值