leetcode-25 Reverse Nodes in k-Group

来源:互联网 发布:vip影院软件下载 编辑:程序博客网 时间:2024/05/16 01:24

问题描述

Given a linked list, reverse the nodes of a linkedlist k at a time and return its modifiedlist.

If the number of nodes is not a multiple of k then left-out nodes in the end shouldremain as it is.

You may not alter the values in the nodes, only nodesitself 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

 

问题分析

该问题可以转化为反转链表的子问题

(http://blog.csdn.net/woliuyunyicai/article/details/45027883)

根据题设需要依据k的值将原链表分为多个分组进行反转;而且要注意前后链表之间的连接。因此需要记录前后分组信息,记录前一个分组preGroup的尾节点,记录后一个分许nextGroup的头节点,然后再将当前分组反转后的链表与前后链表链接到一起。

 

代码

class ListNode {    int val;    ListNodenext;     public ListNode (int val) {        this.val = val;    }} public classSolution {    public ListNodereverseKGroup(ListNode head, int k) {        // 直接返回结果的情况        if (k == 1 || head == null || head.next == null)            return head;        // 辅助节点,用以返回最终的结果        ListNoderesultNode = newListNode(0);        resultNode.next = head;         // 记下每一层的首节点,以及尾节点        ListNodetailNode = head;        ListNodeheadNode = head;         // 记下前一分组尾节点、后一分组的头节点        ListNodepreGroup = resultNode;        ListNodenextGroup = resultNode;         // 每一层分组进行计数        int count = 1;         while (tailNode != null) {            // 到达该分组的尾部,对该分组进行反转            if (count == k) {                // 记录下一分组的头节点                nextGroup= tailNode.next;                // 翻转本分组链表                reverseList(headNode,tailNode);                // 注意翻转后tailNode则为当前分组的头节点,headNode为尾节点                // 链接上一分组、下一分组                preGroup.next = tailNode;                headNode.next = nextGroup;                 // 准备下一层循环                preGroup= headNode;                headNode= nextGroup;                tailNode= nextGroup;                count= 1;                continue;            }            count++;            // 一直向下循环找到该分组的最后一个节点            tailNode= tailNode.next;        }         return resultNode.next;    }     // 反转链表    private void reverseList(ListNodehead, ListNode tail) {        ListNodepreNode = newListNode(0);        preNode.next = head;        ListNodesucNode = null;         // 这里不同于一般的反转链表题目,这里可以不用考虑为null的情况        while (preNode != tail) {            sucNode= head.next;            head.next = preNode;             preNode= head;            head= sucNode;        }    } }

0 0
原创粉丝点击