链表编程题专题--Reverse Nodes in k-Group(最后几个节点不足一组的不逆序)

来源:互联网 发布:mv录制软件 编辑:程序博客网 时间:2024/04/26 22:52

1.题目

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 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个节点一组内部逆序,最后不足k个的不逆序。最后输出逆序后链表的头结点。
(来源于leetCode)

2.解法

为了实现逻辑方便,本题用ArrayList存每个节点的值,然后对每k个元素进行逆序。该方法需要和链表长度相等的空间,若想空间复杂度为常数级别,可直接对链表进行逆序操作,但实现比较复杂,易出错,具体可参考我的另一篇博客:链表编程专题–分组逆序链表。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        ArrayList<Integer> arrayList = new ArrayList<>();        // 将所有节点的值依次存入ArrayList        while (head != null) {            arrayList.add(head.val);            head = head.next;        }        int size = arrayList.size();        // 已经逆序完的结点数量        int sumNumber = 0;        while (sumNumber < size) {            // 如果接下来剩余元素不足k个,则不需逆序,直接结束            if (sumNumber + k > size) {                break;            }else {                // 对序号为[sumNumber,sumNumber + k)区间内的元素进行逆序                reverseSingle(arrayList,sumNumber,sumNumber + k);                sumNumber += k;            }        }        ListNode newHead = new ListNode(0);        ListNode nowNode = newHead;        ListNode nextNode = null;        // 将逆序好的ArrayList整理成链表        for (int i = 0; i < size; i++) {            nextNode = new ListNode(arrayList.get(i));            nowNode.next = nextNode;            nowNode = nextNode;        }        return newHead.next;    }    // 逆序ArrayList从begin到end的元素    public static void reverseSingle(ArrayList<Integer> arrayList,int begin ,int end) {        int temp = -1;        for (int i = 0; i < (end - begin) / 2; i++) {            temp = arrayList.get(end - i - 1 );            arrayList.set(end - i - 1, arrayList.get(begin + i));            arrayList.set(begin + i, temp);        }    }}
原创粉丝点击