链表编程题专题--Reverse Nodes in k-Group(最后几个节点不足一组的不逆序)
2017-08-25 00:56
471 查看
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); } } }
相关文章推荐
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- LeetCode 25 Reverse Nodes in k-Group K个一组反转节点
- LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)
- Reverse Nodes In K Group,将链表每k个元素为一组进行反转---特例Swap Nodes in Pairs,成对儿反转
- [LeetCode] Reverse Nodes in k-Group 每k个一组翻转链表
- [Leetcode] Reverse nodes in k group 每k个一组反转链表
- [LintCode] Reverse Nodes in k-Group 每k个一组翻转链表
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- 【leetcode 链表相关】Reverse Nodes in k-Group
- Reverse Nodes in k-Group 指针操作 每k个翻转链表
- LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)(Linked List)(*)
- Reverse Nodes in k-Group k个数为一组翻转结点
- LeetCode Reverse Nodes in k-Group(单链表连续分段反转)
- Reverse Nodes in k-Group k-group翻转链表@LeetCode
- LeetCode刷题笔记(链表):reverse-nodes-in-k-group
- Reverse Nodes in k-Group [逆转K-Group链表]
- LeetCode OJ:Reverse Nodes in k-Group(K个K个的分割节点)
- Reverse Nodes in k-Group (链表)