题解 | #牛牛的链表交换#
牛牛的链表交换
https://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <iostream> #include <regex> using namespace std; struct Node { int val; Node* next; Node(): val(0), next(nullptr) {} Node(int val): val(val), next(nullptr) {} Node(int val, Node* next): val(val), next(next) {} } ; void changeNode(Node* dummy, int ind) { Node* node1Pre = dummy; int i = 0; while (node1Pre != nullptr && i != ind - 1) { node1Pre = node1Pre->next; ++i; } Node* node1 = node1Pre->next; Node* node2 = node1->next; node1Pre->next = node2; Node* temp = node2->next; node2->next = node1; node1->next = temp; } int main() { int n; cin >> n; int i = 0; Node* dummy = new Node(); Node* node = dummy; while (i != n) { int d; cin >> d; node->next = new Node(d); node = node->next; i++; } changeNode(dummy, 1); changeNode(dummy, n - 1); node = dummy->next; while (node != nullptr) { cout << node->val << " "; node = node->next; } return 0; } // 64 位输出请用 printf("%lld")
按照题解模拟就可以了