赞
踩
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例 2:
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
示例 3:
输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]
示例 4:
输入:head = [1], k = 1
输出:[1]
提示:
解题思路:
即如何反转列表问题
代码实现:
- import java.util.*;
-
- public class Helloworld {
-
- public ListNode reverseKGroup(ListNode head, int k) {
- ListNode hair = new ListNode(0);
- hair.next = head;
- ListNode pre = hair;
-
- while (head != null){
- ListNode tail = pre;
- for (int i = 0; i < k; i++) {
- tail = tail.next;
- if (tail == null)
- return hair.next;
- }
- ListNode nex = tail.next;
- ListNode[] reverse = myReverse(head,tail);
- head = reverse[0];
- tail = reverse[1];
-
- pre.next = head;
- tail.next = nex;
- pre = tail;
- head = tail.next;
- }
- return hair.next;
- }
-
- //反转子列表
- public ListNode[] myReverse(ListNode head, ListNode tail){
- ListNode prev = tail.next;
- ListNode p = head;
- while (prev != tail){
- ListNode nex = p.next;
- p.next = prev;
- prev = p;
- p = nex;
- }
- return new ListNode[]{tail,head};
- }
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String string = scanner.nextLine();
- int k = scanner.nextInt();
- String[] str = string.split(" ");
- int[] nums = new int[str.length];
- for (int i = 0; i < str.length; i++) {
- nums[i] = Integer.parseInt(str[i]);
- }
- ListNode head = new ListNode(nums[0]);
- ListNode pre = head;
- for (int i = 1; i < nums.length; i++) {
- ListNode node = new ListNode(nums[i]);
- pre.next = node;
- pre = node;
- }
-
- ListNode res = new Helloworld().reverseKGroup(head,k);
- while (res != null){
- System.out.println(res.data);
- res = res.next;
- }
- }
- }
- //定义链表结点类
- class ListNode{
- int data;
- ListNode next;
- public ListNode(int data) {
- this.data = data;
- this.next = null;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。