zoukankan      html  css  js  c++  java
  • Palindrome Linked List

    Palindrome Linked List

    问题:

    Given a singly linked list, determine if it is a palindrome.

    Follow up:
    Could you do it in O(n) time and O(1) space?

    思路:

      先选择中间的节点+反转链表

    我的代码:

    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null)    return true;
            
            ListNode mid = getMiddle(head);
            ListNode reverse = getReverse(mid);
            
            while(head!=null && reverse!=null)
            {
                if(head.val == reverse.val)
                {
                    head = head.next;
                    reverse = reverse.next; 
                }
                else return false;
            }
            
            return true;
            
        }
        public ListNode getMiddle(ListNode head)
        {
            ListNode slow = head;
            ListNode fast = head.next;
            while(fast!=null && fast.next!=null)
            {
                fast = fast.next.next;
                slow = slow.next;
            }
            return slow;
        }
        public ListNode getReverse(ListNode head)
        {
            ListNode dummy = new ListNode(-1);
            while(head != null)
            {
                ListNode next = head.next;
                head.next = dummy.next;
                dummy.next = head;
                head = next;
            }
            return dummy.next;
        }
    }
    View Code

    反思:

    • 反转链表好久没写了,竟然都忘记了,代码果然好久没写就是不行啊,幸好在同学的指导下面又重新学会了。
    • palindrome的方法就是反转,从头开始反转,从中间反转,让反转后的等于前面的反转。
  • 相关阅读:
    Daily Scrum 10.29
    Daily Scrum 10.28
    git第一次commit代码阅读
    软工课程项目-数据库管理
    [Go]字典(map)的操作和约束
    [Go]链表的相关知识
    Kubernetes网络设计原则
    [Go]程序实体
    [Kubernetes]集群配置免密登录Permission denied (publickey,password) 解决办法
    [Go]GOPATH相关知识点
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4658404.html
Copyright © 2011-2022 走看看