zoukankan      html  css  js  c++  java
  • 【数据结构与算法】链表——回文链表

    回文链表

    LeetCode:回文链表

    题目描述:

    判断一个链表是否为回文链表。

    示例:

    输入: 1->2->2->1
    输出: true
    

    思想:

    先用快慢指针取得中间位置的指针,将后半段链表进行翻转,再遍历比较前半段和后半段是否一致。时间复杂度O(3/2n),空间复杂度O(1)

    优化:在快慢指针的循环中,同时翻转前半段链表,随后从中间位置往两头遍历,时间复杂度O(n)

    代码:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null||head.next==null)
                return true;
            ListNode mid=head,end=head;
            while(end!=null&&end.next!=null){
                mid = mid.next;
                end = end.next.next;
            }
            ListNode p=mid,q=mid.next,t;
            while(q!=null){
                t=q.next;
                q.next=p;
                p=q;q=t;
            }
            q=head;
            while(q!=mid){
                if(q.val!=p.val)
                    return false;
                q=q.next;
                p=p.next;
            }
            return true;
        }
    }
    

    优化版,但是代码着实有点复杂,没有上一种方法直白

    class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null||head.next==null)
                return true;
            ListNode mid=head,end=head.next,q=head.next,t;
            while(end!=null&&end.next!=null){
                end = end.next.next;
                t = q.next;
                q.next = mid;
                mid = q;q = t;
            }
            ListNode p=(end==null)?mid.next:mid;
            while(q!=null){
                if(q.val!=p.val)
                    return false;
                q=q.next;
                p=p.next;
            }
            return true;
        }
    }
    
  • 相关阅读:
    数据类型之间的转换
    博客园页面美化全系列
    drf——django的缓存和信号
    PEP8规范
    drf——drf局部使用,全局使用顺序
    drf—— xadmin的使用
    drf—— Book系列连表接口
    drf—— base64加码与解码
    drf——小知识
    drf—— 响聊聊cookie session token的演变
  • 原文地址:https://www.cnblogs.com/buptleida/p/12684073.html
Copyright © 2011-2022 走看看