判断单链表是否为回文链表(Java)

判断单链表是否为回文链表

(牛客网—牛客题霸算法篇—NC96)

题目描述

给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。

思路

Java实现
方法一:遍历
定义三个指针,分别为left、right和move,left指向链表前半部分的当前要比较的节点,right指向后半部分的当前要比较的节点,由于单链表不能寻找前一节点,使用move指针寻找right节点。
优点:简单容易理解
缺点:时间耗费较多,只适合于较短的链表。
方法二:栈
栈是一种先进后出的数据结构,我们把链表中的数据全部存入到栈中,这样依次出栈时就相当于逆序访问链表了。
在存入数据时,可以顺便计算链表的长度,这样在出栈比较时就只需要比较一般的数据,更加节省时间。

代码实现

方法一:暴力遍历

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        if(head==null||head.next==null){
            return true;
        }
        int n=1;
        ListNode left=head;
        ListNode right=head;
        ListNode move=head;
        while(move.next!=null){
            n++;
            move=move.next;
        }
        right=move;
        for(int i=0;i<n/2;i++){
            move=left;
            if(left.val!=right.val){
                return false;
            }
            while(move.next!=right){
                move=move.next;
            }
            left=left.next;
            right=move;
        }
        return true;
    }
}

方法二:使用栈

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        if(head==null||head.next==null){
            return true;
        }
        ListNode list=head;
        Stack<Integer> stack=new Stack();
        int len =0;
        while(list!=null){
            stack.push(list.val);
            list=list.next;
            len++;
        }
        len=len/2;
        while(len>=0){
            if(head.val!=stack.pop()){
                return false;
            }
            head=head.next;
            len--;
        }
        return true;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值