Issue 6: The Secret of Palindrome Rotation in Linked List


Brush questions sixth issue
PS: The solution to each question is not unique, welcome to discuss! After each question, there is an analysis to help you analyze and solve the question. The answer is at the bottom, and the bloggers will continue to update it every day.

1. Reverse linked list

Title description:
Give you the head node head of the singly linked list, please reverse the linked list and return the reversed linked list.
Example 1:
12345
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
12
Input: head = [1,2]
Output: [2,1]
Analysis:
We can directly traverse the linked list using iteration, create a cur node equal to head, exchange node tmp, tmp can be null at the beginning, then use cur node to traverse the linked list, use curnext to record cur.next each time, and then let cur.next point to tmp, tmp is equal to cur for the next exchange, and cur is equal to curnext for traversal.

2. Palindrome list

Title description:
You are given a head node head of a singly linked list, please judge whether the linked list is a palindrome linked list. If yes, return true; otherwise, return false.
Example 1:
palindrome
Input: head = [4,3,5,7,5,3,4]
Output: true
Example 2:
Non-palindromic
Input: head = [4,3,5,7]
Output: false
Analysis:
This question is It is equivalent to the advancement of 1, a total of three steps:

  1. Use the fast and slow pointers to find the midpoint of the linked list.
  2. Second half in reverse order.
  3. From the beginning, the middle point, start to compare whether they are the same.

the code

1. Reverse linked list

    public ListNode reverseList(ListNode head) {
    
    
        if(head == null || head.next == null){
    
    
            return head;
        }
        ListNode cur = head;
        ListNode tmp = null;
        while(cur != null){
    
    
            ListNode curnext = cur.next;
            cur.next = tmp;
            tmp = cur;
            cur = curnext; 
        }
        return tmp;
    }

2. Palindrome list

    public boolean isPalindrome(ListNode head) {
    
    
        if(head == null || head.next == null){
    
    
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
    
    
            fast = fast.next.next;
            slow = slow.next; 
        }
        ListNode cur = slow;
        ListNode tmp = null;
        while(cur != null){
    
    
            ListNode curnext = cur.next;
            cur.next = tmp;
            tmp = cur;
            cur = curnext;
        }
        while(tmp != null){
    
    
            if(tmp.val != head.val){
    
    
                return false;
            }
            tmp = tmp.next;
            head = head.next;
        }
        return true;
    }

Guess you like

Origin blog.csdn.net/weixin_73392477/article/details/131199827