fast cin/cout

std::ios::sync_with_stdio(false); //关闭同步之后就不能同时混用printf

std::cin.tie(0);

#define fast_io ios_base::sync_with_stdio(0);
#include <iostream> #include <sstream> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr || head->next == nullptr) return head; int length = 0; ListNode* p = head; while (p != nullptr) { length++; p = p->next; } k = k % length; if (k == 0) return head; ListNode* fast = head; for (int i = 0; i < k; ++i) { fast = fast->next; } ListNode* slow = head; while (fast->next != nullptr) { slow = slow->next; fast = fast->next; } ListNode* newHead = slow->next; slow->next = nullptr; fast->next = head; return newHead; } }; void printList(ListNode* head) { while (head != nullptr) { cout << head->val << " "; head = head->next; } cout << endl; } int main() { // 读取输入 vector<int> nums; string line; cout << "输入链表元素 (空格分隔,如:1 2 3 4 5): "; getline(cin, line); istringstream iss(line); int num; while (iss >> num) { nums.push_back(num); } cout << "输入旋转次数 k: "; int k; cin >> k; // 构建链表 ListNode* head = nullptr; ListNode* tail = nullptr; for (int num : nums) { if (!head) { head = new ListNode(num); tail = head; } else { tail->next = new ListNode(num); tail = tail->next; } } // 执行旋转 Solution sol; ListNode* newHead = sol.rotateRight(head, k); // 输出结果 cout << "旋转后链表: "; printList(newHead); // 内存释放(可选) while (newHead) { ListNode* temp = newHead; newHead = newHead->next; delete temp; } return 0; }不要用到#include <sstream> #include <vector>
04-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值