zoukankan      html  css  js  c++  java
  • 回文链表

    题目

    给定一个链表的头节点head,请判断该链表是否为回 文结构。
    例如: 1->2->1,返回true。
    1->2->2->1,返回true。
    15->6->15,返回true。
    1->2->3,返回false。
    进阶:
    如果链表长度为N,时间复杂度达到O(N),额外空间复杂 度达到O(1)。

    代码实现:

    //快慢指针,都是从头开始

    public class IsPalindromeList {
    public boolean isPalindrome(ListNode head) {
    if(head == null || head.next == null) {
    return true;
    }
    ListNode slow = head, fast = head;
    ListNode pre = head, prepre = null;
    while(fast != null && fast.next != null) {
    pre = slow;
    slow = slow.next;
    fast = fast.next.next;
    pre.next = prepre;
    prepre = pre;
    }
    if(fast != null) {
    slow = slow.next;
    }
    while(pre != null && slow != null) {
    if(pre.val != slow.val) {
    return false;
    }
    pre = pre.next;
    slow = slow.next;
    }
    return true;
    }
    }

    class ListNode {
    int val;
    // 下一个链表对象
    ListNode next;
    //赋值链表的值
    ListNode(int x) { val = x; }

    }
    代码实现2:
    //快慢指针,反转前半部分链表,时间O(n),空间O(1)
    /**用2个指针,一个low,一个fast,fast是low的2倍,所以可以达到2分链表的效果
    *,在移动指针时同时对前半部分链表进行反转。最后直接比较被分开的2个链表
    *因为不能改变当前slow的next,不然就无法跳到下一个元素,所以这里用pre和prepre实现指针的反转
    *时间复杂度:第一个循环O(n/2),第2个循环O(n/2)
    */
     
    public class IsPalindromeList {
    public boolean isPalindrome(ListNode head) {
    if(head == null || head.next == null) return true;
    ListNode slow = head, fast = head.next, pre = null, prepre = null;
    while(fast != null && fast.next != null) {
    //反转前半段链表
    pre = slow;
    slow = slow.next;
    fast = fast.next.next;
    //先移动指针再来反转
    pre.next = prepre;
    prepre = pre;
    }
    ListNode p2 = slow.next;
    slow.next = pre;
    ListNode p1 = fast == null? slow.next : slow;
    while(p1 != null) {
    if(p1.val != p2.val) {
    return false;
    }
    p1 = p1.next;
    p2 = p2.next;
    }
    return true;
    }

    }

    class ListNode {
    int val;
    // 下一个链表对象
    ListNode next;
    //赋值链表的值
    ListNode(int x) { val = x; }

    }
     
  • 相关阅读:
    vue 组件传值
    ES6 解构赋值
    JS filter的使用
    FormData实现文件上传
    vue+element 表格导出Excel文件
    vue2.0 element-ui中input的@keyup.native.enter='onQuery'回车查询刷新整个表单的解决办法
    vue2.0 element-ui中el-upload的before-upload方法返回false时submit()不生效解决方法
    JavaScript正则表达式检验手机号码、邮箱、ip地址等
    Vue 2.0 pagination分页组件
    angular环境
  • 原文地址:https://www.cnblogs.com/cdlyy/p/12081579.html
Copyright © 2011-2022 走看看