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

【题目】

	给定一个链表的头节点head,前判断该链表是否为回文结构
	例如:
	1 -> 2 -> 1,返回true
	1 -> 2 -> 2 -> 1,返回true
	1 -> 2 -> 3,返回false

【代码1,空间复杂度n】

    public boolean isPalindrome(ListNode head) {
        ListNode cur = head;
        Stack<Integer> stack = new Stack<Integer>();
        while(cur != null){
            stack.push(cur.val);
            cur = cur.next;
        }
        while(head != null){
            if(head.val != stack.pop()){
                return false;
            }
            head = head.next;
        }
        return true;
    }

【代码2,空间复杂度为n/2】

   public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null){
            return true;
        }
        Stack<Integer> stack = new Stack<Integer>();
        ListNode right = head.next;
        ListNode cur = head;
        while(cur.next != null && cur.next.next != null){
            right = right.next;
            cur = cur.next.next;
        }
        while(right != null){
            stack.push(right.val);
            right = right.next;
        }   
        while(!stack.isEmpty()){
            if(stack.pop() != head.val){
                return false;
            }
            head = head.next;
        }
        return true;
    }

【代码3,空间复杂度O(1)】

    public boolean isPalindrome(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 = null;
        while(n2 != null){
            n3 = n2.next;
            n2.next = n1;
            n1 = n2;
            n2 = n3;
        }
        boolean res = true;
        n3 = n1; //保存最后一个节点
        n2 = head;
        while(n2 != null && n1 != null){
            if(n2.val != n1.val){
                res = false;
                break;
            }
            n2 = n2.next;
            n1 = n1.next; 
        }
        n1 = null;
        while(n3 != null){
            n2 = n3.next;
            n3.next = n1;
            n1 = n3;
            n3 = n2;
        }
        return res;
        
    }
©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值