美文网首页
LeetCode每日一题:reverse nodes in k

LeetCode每日一题:reverse nodes in k

作者: yoshino | 来源:发表于2017-07-04 11:46 被阅读12次

    问题描述

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
    If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
    You may not alter the values in the nodes, only nodes itself may be changed.
    Only constant memory is allowed.
    For example,
    Given this linked list:1->2->3->4->5
    For k = 2, you should return:2->1->4->3->5
    For k = 3, you should return:3->2->1->4->5

    问题分析

    逆转链表的前k位,没有什么难度。

    代码实现

    public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k < 2) return head;
            ListNode first = new ListNode(-1);
            first.next = head;
            ListNode pre = first;
            ListNode cur = head;
            ListNode temp = null;
            int len = 0;
            while (head != null) {
                head = head.next;
                len++;
            }
            int count = len / k;
            while (count-- > 0) {
                int c = k;
                while (c-- > 1) {
                    temp = cur.next;
                    cur.next = temp.next;
                    temp.next = pre.next;
                    pre.next = temp;
                }
                pre = cur;
                cur = cur.next;
            }
            return first.next;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:reverse nodes in k

          本文链接:https://www.haomeiwen.com/subject/zlgthxtx.html