以下是使用C++实现含头结点的单链表,并实现元素位置移动的代码示例:
#include <iostream>
// 定义单链表节点结构体
struct Node {
int data;
Node* next;
};
// 创建含有头结点的单链表
Node* createLinkedList(int n) {
Node* head = new Node(); // 创建头结点
Node* tail = head; // 指向尾节点
for (int i = 0; i < n; i++) {
int value;
std::cin >> value;
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
tail->next = newNode;
tail = newNode;
}
return head;
}
// 打印单链表
void printLinkedList(Node* head) {
Node* current = head->next;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// 获取链表长度
int getLinkedListLength(Node* head) {
int length = 0;
Node* current = head->next;
while (current != nullptr) {
length++;
current = current->next;
}
return length;
}
// 移动元素位置
void moveElement(Node* head, int pos1, int pos2) {
if (pos1 == pos2 || pos1 <= 0 || pos2 <= 0)
return;
int length = getLinkedListLength(head);
if (pos1 > length || pos2 > length)
return;
if (pos1 > pos2)
std::swap(pos1, pos2);
Node* prev1 = nullptr;
Node* prev2 = nullptr;
Node* current = head->next;
for (int i = 0; i < pos1 - 1; i++) {
prev1 = current;
current = current->next;
}
for (int i = 0; i < pos2 - 1; i++) {
prev2 = current;
current = current->next;
}
if (prev1 != nullptr)
prev1->next = current;
if (prev2 != nullptr)
prev2->next = prev1 == nullptr ? head : prev1;
Node* tempNext = current->next;
current->next = prev1 == nullptr ? tempNext : prev1->next;
if (prev2 == nullptr)
head->next = current;
}
int main() {
int n, t;
std::cin >> n;
Node* head = createLinkedList(n);
std::cin >> t;
std::cout << "Original List: ";
printLinkedList(head);
for (int i = 0; i < t; i++) {
int pos1, pos2;
std::cin >> pos1 >> pos2;
moveElement(head, pos1, pos2);
std::cout << "After Move " << i + 1 << ": ";
printLinkedList(head);
}
return 0;
}
请注意,此代码是基于题目要求实现的,并包含了错误处理逻辑。你可以根据需要进行修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问




