[LeetCode] 234. 回文链表 ☆(翻转链表)

描述

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

示例 1:

输入: 1->2
输出: false
示例 2:

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


进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解析

回文的意思,比如 1->2->2->1是回文链表;1->2->3->2->1也是。要满足上面的时间、空间复杂度,需要翻转前半部分的链表,与后半部分的链表比较。

步骤:

1. 找出中间节点;

2.翻转前半部分节点;

3.与后半部分节点一一比较。

优化点:

将步骤1、2合并,边找中间节点边翻转。

代码

例子:

1 2 3 4
slow = 2 fast = 3
slow = 3 fast = null pre=2

1 2 3 4 5
slow = 2 fast = 3
slow = 3 fast = 5 pre=2

/**
 * 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 last = null;
        ListNode pre = head;
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;

            pre.next = last;
            last = pre;
        }

        ListNode rightStart;
        if (fast == null) {//说明偶数节点
            rightStart = slow;
        } else {
            rightStart = slow.next;
        }

        ListNode leftStart = pre;
        while (leftStart != null && rightStart != null) {
            if (leftStart.val != rightStart.val) {
                return false;
            }
            leftStart = leftStart.next;
            rightStart = rightStart.next;
        }
        if (leftStart != null || rightStart != null) {
            return false;
        }
        return true;
    }
    
//正常思路,一步一步来
public boolean isPalindrome1(ListNode head) { if (head == null || head.next == null) { return true; } ListNode pre = head; ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) {//找中间节点 pre = slow; slow = slow.next; fast = fast.next.next; } pre.next = null; ListNode rightStart; if (fast == null) {//说明偶数节点 rightStart = slow; } else { rightStart = slow.next; } ListNode leftStart = reserver(head);//翻转前半部分链表 while (leftStart != null && rightStart != null) {//一一比较 if (leftStart.val != rightStart.val) { return false; } leftStart = leftStart.next; rightStart = rightStart.next; } if (leftStart != null || rightStart != null) { return false; } return true; } //翻转链表 public ListNode reserver(ListNode head) { if (head == null) { return head; } ListNode pre = null; ListNode cur = head; ListNode next; while (cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/11366155.html