LeetCode每日一题:reverse nodes in k

2017-07-04  本文已影响12人  yoshino

问题描述

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;
    }
上一篇下一篇

猜你喜欢

热点阅读