力扣labuladong一刷day15天K个一组翻转链表与回文链表

力扣labuladong一刷day15天K个一组翻转链表与回文链表

一、25. K 个一组翻转链表

题目链接:https://leetcode.cn/problems/reverse-nodes-in-k-group/
思路:k个一组翻转链表,每k个翻转抽取出一个单独的方法reverse,翻转a到b,返回的结果是新的头结点。
然后递归调用reverseKGroup,每次返回的都是新的头结点,新的头结点要接在上一个尾结点的位置也就是未翻转前的head即a。

class Solution {
   public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) return null;
        ListNode a = head, b = head;
        for (int i = 0; i < k; i++) {
            if (b == null) return a;
            b = b.next;
        }
        ListNode newHead = reverse(a, b);
        a.next = reverseKGroup(b, k);
        return newHead;
    }

    ListNode reverse(ListNode a, ListNode b) {
        ListNode pre = null, cur = a, nex = b;
        while (cur != b) {
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        return pre;
    }
}

二、234. 回文链表

题目链接:https://leetcode.cn/problems/palindrome-linked-list/
思路:类比于字符串,如果是判断是否是回文,只需要从两端向中间进行逐个比较,如果是寻找回文子串则要考虑奇数偶数从中间向两端寻找。

这里是判断链表是否是回文链表。只需要用一个全局变量记录head值,然后递归后序遍历,逐个比较。

ListNode left = null;
    public boolean isPalindrome(ListNode head) {
        left = head;
        return reverse(head);
    }

    boolean reverse(ListNode right) {
        if (right == null) return true;
        boolean res = reverse(right.next);
        res = res && left.val == right.val;
        left = left.next;
        return res;
    }

但这样其实是多比较了一半,也可以先试用快慢指针找到中点,然后翻转后一半,再来逐个比较,只要右边短的停止了就停止。

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head, fast = head, left = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        if (fast != null) slow = slow.next;
        slow = reverse(slow);
        while (slow != null) {
            if (left.val != slow.val) return false;
            left = left.next;
            slow = slow.next;
        }
        return true;
    }

    ListNode reverse(ListNode node) {
        ListNode pre = null, cur = node, nex = node;
        while (cur != null) {
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        return pre;
    }
}

你可能感兴趣的:(力扣算法题,leetcode,链表,算法)