判断链表是否是回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

public static class Node{
    public int value;
    public Node next;
    public Node(int data){
        value = data;
    }
}
  1. 使用栈做辅助空间,额外需要n个空间

public static boolean isPalindromeList1(Node head){
    Stack<Node> stack = new Stack<>();
    Node cur = head;
    while(cur != null){
        stack.push(cur);
        cur = cur.next;
    }
    while(head != null){
        if(head.value == stack.pop().value){
            head = head.next;
        }else {
            return false;
        }
    }
    return true;
}
  1. 使用栈做辅助空间,额外需要n/2个空间

public static boolean isPalindromeList2(Node head){
    if(head == null || head.next == null){
        return true;
    }
    Node slow = head;
    Node fast = head.next;
    while(fast.next != null && fast.next.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    Stack<Node> stack = new Stack<>();
    while(slow != null){
        stack.push(slow);
        slow = slow.next;
    }
    while(!stack.isEmpty()){
        if(head.value == stack.pop().value){
            head = head.next;
        }else {
            return false;
        }
    }
    return true;
}
  1. 不使用额外辅助空间,运用链表翻转判断回文链表,空间复杂度O(1)

public static boolean isPalindromeList3(Node head){
    if(head == null || head.next == null){
        return true;
    }
    Node n1 = head;
    Node n2 = head;
    while(n2.next != null && n2.next.next != null){
        n1 = n1.next;   // n1->mid
        n2 = n2.next.next;  // n2->end
    }

    n2 = n1.next;   // n2 -> right part first node
    n1.next = null; // mid.next -> null
    Node n3 = null;
    while(n2 != null){  // 右侧链表翻转
        n3 = n2.next;   // n3 -> save next node
        n2.next = n1;   // next of right node convert
        n1 = n2;    // n1 move
        n2 = n3;    // n2 move
    }
    n3 = n1;    // n3 -> save last node
    n2 = head;  // n2 -> left first node
    boolean res = true;
    while(n1 != null && n2 != null){    // 检查是否是回文链表
        if(n1.value != n2.value){
            res = false;
            break;
        }
        n1 = n1.next;   // left to mid
        n2 = n2.next;   // right to mid
    }
    n1 = n3.next;
    n3.next = null;
    while(n1 != null){  // recover list
        n2 = n1.next;
        n1.next = n3;
        n3 = n1;
        n1 = n2;
    }
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值