LeetCode开心刷题十四天——25Reverse Nodes in k-Group

叁歲伎倆 2023-08-17 15:14 160阅读 0赞
  1. Reverse Nodes in k-Group

Hard

1222257FavoriteShare

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed

改进声明:

本方法速度和内存好像都比较差,虽然思路简洁,但是可能构造技巧上还是有进步空间

1005283-20190707103635694-588232289.png

main idea:

One word to sum up the idea,victory! haaa~just a joke

Group

In this reverse problem,group is important,devide into ordered &inordered.three pointers we need to correctly understanding the meaning of these variables.cur->ordered part end ,nxt->inordered start,pre->before these parts.

It looks like this composition:

pre->order part->inorder part->left_out

Now it’s the code

  1. #include <iostream>
  2. #include<vector>
  3. #include<iostream>
  4. #include<string>
  5. #include<stdio.h>
  6. #include<string.h>
  7. #include<iomanip>
  8. #include<vector>
  9. #include<list>
  10. #include<queue>
  11. #include<algorithm>
  12. #include<stack>
  13. #include<map>
  14. using namespace std;
  15. struct ListNode {
  16. int val;
  17. ListNode *next;
  18. ListNode(int x) : val(x), next(NULL) {}
  19. };
  20. class Solution {
  21. public:
  22. ListNode* reverseKGroup(ListNode* head, int k) {
  23. //this situation can include head->next
  24. //special case dispose
  25. if(!head||k==1) return head;
  26. //dummy node
  27. ListNode dummy(0);
  28. dummy.next=head;
  29. //len calc
  30. int len=1;
  31. while(head=head->next) len++;
  32. //cout<<len<<endl;
  33. ListNode *pre=&dummy;
  34. for(int i=0;i+k<=len;i+=k)
  35. {
  36. ListNode *cur=pre->next;
  37. ListNode *nxt=cur->next;
  38. for(int j=1;j<k;j++)
  39. {
  40. cur->next=nxt->next;
  41. nxt->next=pre->next;
  42. pre->next=nxt;
  43. nxt=cur->next;
  44. }
  45. pre=cur;
  46. }
  47. return dummy.next;
  48. }
  49. };
  50. int main()
  51. {
  52. int k;
  53. cin>>k;
  54. ListNode a(1);
  55. ListNode b(2);
  56. ListNode c(3);
  57. ListNode d(4);
  58. ListNode e(5);
  59. Solution s;
  60. a.next=&b;
  61. b.next=&c;
  62. c.next=&d;
  63. d.next=&e;
  64. ListNode *head=&a;
  65. // while(head)
  66. // {
  67. // cout<<head->val<<endl;
  68. // head=head->next;
  69. // }
  70. ListNode* res=NULL;
  71. res=s.reverseKGroup(head, k);
  72. while(res)
  73. {
  74. cout<<res->val<<endl;
  75. res=res->next;
  76. }
  77. return 0;
  78. }

转载于:https://www.cnblogs.com/Marigolci/p/11145448.html

发表评论

表情:
评论列表 (有 0 条评论,160人围观)

还没有评论,来说两句吧...

相关阅读