以下是用C++实现含头结点的单链表,并根据输入要求进行插入操作的示例代码:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* createLinkedList(int n) {
ListNode* head = new ListNode(0); // 头结点
ListNode* curr = head;
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
ListNode* newNode = new ListNode(num);
curr->next = newNode;
curr = newNode;
}
return head;
}
void printLinkedList(ListNode* head) {
if (!head)
return;
ListNode* curr = head->next; // 跳过头结点
while (curr) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
bool isValidPosition(ListNode* head, int pos) {
int count = 0; // 计数器
ListNode* curr = head->next; // 跳过头结点
while (curr) {
++count;
if (count == pos)
return true;
curr = curr->next;
}
return false;
}
void insertNode(ListNode* head, int fromPos, int toPos) {
if (!isValidPosition(head, fromPos) || !isValidPosition(head, toPos)) {
cout << "error" << endl;
return;
}
if (fromPos == toPos)
return;
// 找到要移动的节点和其前驱节点
ListNode* fromPrev = head;
for (int i = 0; i < fromPos - 1; ++i)
fromPrev = fromPrev->next;
ListNode* fromNode = fromPrev->next;
ListNode* toPrev = head;
for (int i = 0; i < toPos - 1; ++i)
toPrev = toPrev->next;
// 断开fromNode
fromPrev->next = fromNode->next;
// 将fromNode插入到toPos的前面
ListNode* nextNode = toPrev->next;
toPrev->next = fromNode;
fromNode->next = nextNode;
}
int main() {
int n;
cin >> n;
ListNode* head = createLinkedList(n);
cout << "Original list: ";
printLinkedList(head);
int t;
cin >> t;
while (t--) {
int pos1, pos2;
cin >> pos1 >> pos2;
insertNode(head, pos1, pos2);
cout << "Modified list: ";
printLinkedList(head);
}
return 0;
}
注意:以上代码是基于题目要求实现的简单示例,可能并不完整或最优。在实际情况下,应该考虑更多边界条件和错误处理。
内容由零声教学AI助手提供,问题来源于学员提问