Reverse Nodes in k-Group

来源:互联网 发布:100兆访客网络限速多少 编辑:程序博客网 时间:2024/06/09 18:22

原题:

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

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple ofk 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个为一组的反转。


思考过程:一开始还想按照上次的思路来,和上次相比,这次改变只是多个为一组,所以加上链表反转算法就好。当然判断剩余链表是否够长要多花时间遍历后面k个节点。

后来看到有人用递归思想解决:只需要写好k个节点反转的算法,然后让这一段末尾的next是下一段开头。所以函数返回值是这一段的开头(反转后的)。


解题思路:

链表反转用两个指针是不够的比如:1->2->3->4.,用l1,l2,l3分别标记1,2,3,实现2->1,l1 = l2,l2 = l3,l3 = l3.next。这里l3用于做标记、移动。


结果代码:

public ListNode reverseKGroup(ListNode head, int k) {        ListNode listNode = head;        for (int i = 0;i < k;i++){//判断是否还有k个节点,同时用listNode标记下一段的开始。            if (listNode == null) return head;            listNode = listNode.next;        }        ListNode listNode1 = new ListNode(0);        listNode1.next = head;        ListNode listNode2 = head;        while (listNode2 != listNode){//l2是三个指针的中间一个,用以和listNode比较,判断是否反转了k个节点            ListNode listNode3 = listNode2.next;                listNode2.next = listNode1;                listNode1 = listNode2;                listNode2 = listNode3;        }        head.next = reverseKGroup(listNode2,k);        return listNode1;    }

原创粉丝点击