下面是使用C++实现含头结点的单链表,并实现元素位置的移动的代码:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = new Node();
head->next = nullptr;
}
~LinkedList() {
clear();
delete head;
}
void insert(int val) {
Node* newNode = new Node();
newNode->data = val;
newNode->next = head->next;
head->next = newNode;
}
void move(int currentPos, int targetPos) {
if (currentPos == targetPos)
return;
if (currentPos <= 0 || targetPos <= 0) {
cout << "error" << endl;
return;
}
// Find the nodes at current position and its previous position
Node* currNode = head->next;
Node* prevNode = head;
for (int i = 1; i < currentPos; i++) {
if (currNode == nullptr) { // Invalid current position
cout << "error" << endl;
return;
}
prevNode = currNode;
currNode = currNode->next;
}
// Find the node at target position and its previous position
Node* targetPrevNode = head;
for (int i = 1; i < targetPos; i++) {
if (targetPrevNode == nullptr) { // Invalid target position
cout << "error" << endl;
return;
}
targetPrevNode = targetPrevNode->next;
}
// Move the node from current position to target position
prevNode->next = currNode->next;
currNode->next = targetPrevNode->next;
targetPrevNode->next = currNode;
}
void display() {
Node* curr = head->next;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
void clear() {
Node* curr = head->next;
while (curr != nullptr) {
Node* temp = curr;
curr = curr->next;
delete temp;
}
head->next = nullptr;
}
};
int main() {
int n, t, val, currentPos, targetPos;
cin >> n; // Number of data in the linked list
LinkedList myList;
for (int i = 0; i < n; i++) {
cin >> val; // Input the data
myList.insert(val);
}
cin >> t; // Number of moves
myList.display(); // Output original list
for (int i = 0; i < t; i++) {
cin >> currentPos >> targetPos; // Input move positions
myList.move(currentPos, targetPos);
myList.display(); // Output modified list after each move
}
return 0;
}
你可以使用这段代码实现所需功能,并根据输入输出样例进行测试。
内容由零声教学AI助手提供,问题来源于学员提问




