当前位置:   article > 正文

力扣 25. K 个一组翻转链表(JAVA)_链表分组交换java

链表分组交换java

给你一个链表,每 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]

提示:

  • 列表中节点的数量在范围 sz 内
  • 1 <= sz <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= sz

解题思路:

即如何反转列表问题

代码实现:

  1. import java.util.*;
  2. public class Helloworld {
  3. public ListNode reverseKGroup(ListNode head, int k) {
  4. ListNode hair = new ListNode(0);
  5. hair.next = head;
  6. ListNode pre = hair;
  7. while (head != null){
  8. ListNode tail = pre;
  9. for (int i = 0; i < k; i++) {
  10. tail = tail.next;
  11. if (tail == null)
  12. return hair.next;
  13. }
  14. ListNode nex = tail.next;
  15. ListNode[] reverse = myReverse(head,tail);
  16. head = reverse[0];
  17. tail = reverse[1];
  18. pre.next = head;
  19. tail.next = nex;
  20. pre = tail;
  21. head = tail.next;
  22. }
  23. return hair.next;
  24. }
  25. //反转子列表
  26. public ListNode[] myReverse(ListNode head, ListNode tail){
  27. ListNode prev = tail.next;
  28. ListNode p = head;
  29. while (prev != tail){
  30. ListNode nex = p.next;
  31. p.next = prev;
  32. prev = p;
  33. p = nex;
  34. }
  35. return new ListNode[]{tail,head};
  36. }
  37. public static void main(String[] args) {
  38. Scanner scanner = new Scanner(System.in);
  39. String string = scanner.nextLine();
  40. int k = scanner.nextInt();
  41. String[] str = string.split(" ");
  42. int[] nums = new int[str.length];
  43. for (int i = 0; i < str.length; i++) {
  44. nums[i] = Integer.parseInt(str[i]);
  45. }
  46. ListNode head = new ListNode(nums[0]);
  47. ListNode pre = head;
  48. for (int i = 1; i < nums.length; i++) {
  49. ListNode node = new ListNode(nums[i]);
  50. pre.next = node;
  51. pre = node;
  52. }
  53. ListNode res = new Helloworld().reverseKGroup(head,k);
  54. while (res != null){
  55. System.out.println(res.data);
  56. res = res.next;
  57. }
  58. }
  59. }
  60. //定义链表结点类
  61. class ListNode{
  62. int data;
  63. ListNode next;
  64. public ListNode(int data) {
  65. this.data = data;
  66. this.next = null;
  67. }
  68. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/598303
推荐阅读
相关标签
  

闽ICP备14008679号