反转链表相关算法题

反转链表是最基本的算法题,很多和链表相关的题目都会涉及到。
题解:《剑指offer》系列 反转链表(Java)

LeetCode:92. 反转链表 II

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode pre = head;
        ListNode p = head;
        ListNode first = head, second = head;
        int i = 1;
        while (i <= n) {
            if (i == m - 1) {
                pre = p;
            }
            if (m == i) {
                first = p;
            }
            if (n == i) {
                second = p;
            }
            p = p.next;
            i++;
        }
        reserve(first, second);
        //说明前面翻转链表前没有节点
        if (m == 1) {
            first.next = p;
            return second;
        } else {
            pre.next = second;
            first.next = p;
            return head;
        }
    }

    public ListNode reserve(ListNode first, ListNode second) {
        ListNode prev = null;
        ListNode last = second.next;
        while (first != last) {
            ListNode next = first.next;
            first.next = prev;
            prev = first;
            first = next;
        }
        return prev;
    }
}

LeetCode:25. K 个一组翻转链表

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode p = head;
        ListNode newHead = head;
        ListNode result = head;
        ListNode beforeLast = null;
        int len = 1;
        while (true) {
            int i = 0;
            while (i < k && p != null) {
                p = p.next;
                i++;
            }
            if (i < k) {
                return result;
            } else {
                //一次遍历
                ListNode q = reverse(newHead, k);
                if (beforeLast != null) {
                    beforeLast.next = q;
                }
                if (len == 1) {
                    result = q;
                }
                len++;
                ListNode temp = q;
                int j = 1;
                while (j < k) {
                    j++;
                    temp = temp.next;
                }
                temp.next = newHead = p;
                beforeLast = temp;
            }
        }
    }

    //从当前结点开始  k个链表反转
    private ListNode reverse(ListNode head, int k) {
        ListNode p = null;
        ListNode cur = head;
        int i = 0;
        while (i < k) {
            ListNode temp = cur.next;
            cur.next = p;
            p = cur;
            cur = temp;
            i++;
        }
        return p;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值