Small problem read list

Small problem read list

Foreword

Summer vacation, I take this period of time combing over data structures, today let's take a look at the basic data structure - list. Relatively speaking, I prefer to understand the real problems 数据结构of this abstract concept. music, let's get started!

The first question - palindrome string

Make a list to determine whether the list is a palindrome.

Example 1:

Input: 1-> 2
Output: false

Example 2:

Input: 1-> 2-> 2-> 1
Output: true

Advanced:
You can use O (n) time complexity and O (1) space complexity to solve this problem?

  • Thinking

    Due to resolve the problem in time O (1) space complexity, so I naturally thought of the two-hand method.

    step:

    1. Speed ​​using two pointers, reverse slow walking pointer, when the pointer is fast in the end, the front half of the string to complete the reverse.
    2. Meaning you can compare the two parts
  • Code

    /**
     * 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 prev = null;
            ListNode slow = head;
            ListNode fast = head;
            ListNode next = null;
            while(fast!=null&&fast.next!=null){
                fast = fast.next.next;
                next = slow.next;
                slow.next = prev;
                prev = slow;
                slow = next;
            }
    
            if(fast!=null){
                slow = slow.next;
            }
            while(slow!=null){
                if(slow.val!=prev.val) return false;
                slow = slow.next;
                prev = prev.next;
            }
            return true;
        }
    }

The second question - circular linked list

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

  • Ideas:

    Finger same speed, if the pointer is able to meet the two rings have

  • Code:

    public boolean hasCycle(ListNode head){
        if(!head) return false;
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next!=null && fast.next.next!=null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow)
                return true;
        }
        return false;
    }

to sum up

Of course there are many topics related to the list, you can go to their major OJ ( leetcode , etc.) to explore, there are similar problems, a single list of reverse merger of two ordered list, delete the reciprocal of the list of n nodes , seeking an intermediate node like. These master list that you learn to structure, lay the foundation for future learning!

Guess you like

Origin www.cnblogs.com/jiaweixie/p/11305923.html