题目描述

  • 给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。
  • 例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;
  • 如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。

思路

  • 通过链表长度和K值确定需要反转的结点数
  • 每K个反转成新链表,把头保存到List中
  • 需要反转的结点数已到并且剩下的结点数不足K个,不反转,即把当前结点存到List中
  • 把List中各个链表连接

代码

  1. package com.liuyong666.pat;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class Main {
  5. static class ListNode{
  6. int val;
  7. ListNode next = null;
  8. public ListNode(int val){
  9. this.val = val;
  10. }
  11. }
  12. public static ListNode reversePartNode(ListNode head, int k){
  13. if(head == null || k < 1){
  14. return null;
  15. }
  16. ListNode p = head;
  17. //获取链表长度
  18. int len = 0;
  19. while(p != null){
  20. len++;
  21. p = p.next;
  22. }
  23. ListNode reverseListHead = null;
  24. ListNode curNode = head;
  25. ListNode preNode = null;
  26. ListNode nextNode = null;
  27. //List存放各链表头结点
  28. List<ListNode> list = new ArrayList<ListNode>();
  29. //count 计数器 记录k个元素,每k个重新置1
  30. int count = 1;
  31. //需要发生反转的结点个数
  32. int reverseNum = (len / k) * k;
  33. while(curNode != null){
  34. nextNode = curNode.next;
  35. if( count <= k){
  36. if(count == k){
  37. reverseListHead = curNode;
  38. list.add(reverseListHead);
  39. count = 1;
  40. curNode.next = preNode;
  41. preNode = null;
  42. curNode = nextNode;
  43. }else{
  44. count++;
  45. curNode.next = preNode;
  46. preNode = curNode;
  47. curNode = nextNode;
  48. }
  49. }
  50. if(reverseNum == 1 && count != k){
  51. list.add(curNode);
  52. break;
  53. }
  54. reverseNum--;
  55. }
  56. ListNode newHead = list.get(0);
  57. for(int i = 0; i < list.size() - 1; i++){
  58. p = list.get(i);
  59. while(p.next != null){
  60. p = p.next;
  61. }
  62. p.next = list.get(i + 1);
  63. }
  64. return newHead;
  65. }
  66. }
  67. public static void main(String[] args) {
  68. ListNode node1 = new ListNode(1);
  69. ListNode node2 = new ListNode(2);
  70. ListNode node3 = new ListNode(3);
  71. ListNode node4 = new ListNode(4);
  72. ListNode node5 = new ListNode(5);
  73. ListNode node6 = new ListNode(6);
  74. node1.next = node2;
  75. node2.next = node3;
  76. node3.next = node4;
  77. node4.next = node5;
  78. node5.next = node6;
  79. ListNode p = node1;
  80. while(p != null){
  81. System.out.print(p.val+" ");
  82. p = p.next;
  83. }
  84. System.out.println();
  85. ListNode revNode = reversePartNode(node1, 4);
  86. while(revNode != null){
  87. System.out.print(revNode.val+" ");
  88. revNode = revNode.next;
  89. }
  90. }