Inference from one example to three series of palindrome linked list

The Master said: "If you don't get angry, don't open up, if you don't complain, don't express. If you take one corner and don't use three corners to counter it, then there will be no more."

Now that Internet interviews have become more and more complicated, and at the same time, algorithm inspection is an insurmountable gap for many programmers. In order to help you save time, here is a series of articles by inference .

234. Palindrome Linked List

In order to save time and improve efficiency, only the optimal solution is provided .

The optimal solution to this problem requires us to first solve 876. The intermediate node of the linked list and 206. Reverse the linked list .

1. Problem-solving ideas

  1. Find the middle node of the linked list;
  2. Flip the second half;
  3. Synchronous traversal comparison;

Specific steps

2. Code implementation

class Solution {
    
    
    public boolean isPalindrome(ListNode head) {
    
    
        if(head == null || head.next == null){
    
    
            return true;
        }
        ListNode midNode = middle(head);
        ListNode reversedMidHead = reverse(midNode);
        // 3.循环对比
        while(head != null && reversedMidHead != null){
    
    
            if(head.val != reversedMidHead.val){
    
    
                return false;
            }
            head = head.next;
            reversedMidHead = reversedMidHead.next;
        }
        return true;
    }
    // 1.查找中间节点(若中间节点有2个,则返回后一个。如: 1-->2-->2--1)
    public ListNode middle(ListNode head){
    
    
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
    
    
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    // 2.翻转链表
    public ListNode reverse(ListNode head){
    
    
        ListNode prev = null;
        ListNode cur = head;

        while(cur != null){
    
    
            ListNode tmp = cur.next;

            cur.next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }
}

3. Plan ahead

  1. 876. Intermediate Node of Linked List
  2. 206. Reverse Linked List

Guess you like

Origin blog.csdn.net/wangcheeng/article/details/123016224