力扣 题目61- 旋转链表

题目

题解

化繁为简:

说是旋转但是我们观察可以发现其实就是 将倒数第(k % 链表长度)个开始到最后 将这些放在最前面 

这里我使用了

vector<ListNode*> v; 去保存每一个ListNode*(当然这里也可以不使用vector)

那么最后置换时

 1 (*(v.end() - k - 1))->next = NULL;

2 (*(v.end()-1))->next = *v.begin(); 

代码

 1 #include<iostream>
 2 #include <vector>
 3 using namespace std;
 4 /**
 5  * Definition for singly-linked list. */
 6 struct ListNode {
 7     int val;
 8     ListNode* next;
 9     ListNode() : val(0), next(nullptr) {}
10     ListNode(int x) : val(x), next(nullptr) {}
11     ListNode(int x, ListNode* next) : val(x), next(next) {}
12 };
13 
14 
15 class Solution {
16 public:
17     ListNode* rotateRight(ListNode* head, int k) {
18         if (head == NULL) {
19             return head;
20         }
21         vector<ListNode*> v;
22         ListNode* replace = head;
23         int add = 0;
24         //1.找到全部大小
25         //2.找到倒数k的位置
26         for (; replace != NULL; add++) {
27             v.push_back(replace);
28             replace = replace->next;
29         }
30         k = k % v.size();
31         if (k == 0) {
32             return head;
33         }
34         //置换
35         (*(v.end() - k - 1))->next = NULL;
36         (*(v.end()-1))->next = *v.begin();
37         return *(v.end() - k );
38     }
39 };
40 
41 
42 int main() {
43     Solution sol;
44     struct ListNode head(0);
45     struct ListNode* ergodic = &head;
46     for (int i = 1; i < 2; i++) {
47         struct ListNode* p;
48         p = (struct ListNode*)malloc(sizeof(struct ListNode*));
49         p->val = i;
50         ergodic->next = p;
51         ergodic = ergodic->next;
52     }
53     ergodic->next = NULL;
54     struct ListNode* ergodic2 = sol.rotateRight(&head, 1);
55     for (int i = 0; ergodic2 != NULL; i++) {
56         cout << ergodic2->val << endl;
57         ergodic2 = ergodic2->next;
58     }
59 
60 }
View Code

 

posted @ 2022-05-25 09:59  无聊的阿库娅  阅读(21)  评论(0编辑  收藏  举报