下面是用C++实现含头结点的单链表,并实现了单链表中元素的插入,使用头插法改变项目顺序的例子:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void insert(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
newNode->next = head->next;
head->next = newNode;
}
void printList(ListNode* head) {
ListNode* curr = head->next;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
ListNode* moveElements(ListNode*& head, int srcPos, int destPos) {
if (srcPos == destPos) {
return head;
}
// Find the source node and its previous node
ListNode* prevSrc = head;
for (int i = 0; i < srcPos-1; i++) {
prevSrc = prevSrc->next;
if (prevSrc == NULL || prevSrc->next == NULL) {
return NULL; // Invalid source position
}
}
// Find the destination node and its previous node
ListNode* prevDest = head;
for (int i = 0; i < destPos-1; i++) {
prevDest = prevDest->next;
if (prevDest == NULL || prevDest->next == NULL) {
return NULL; // Invalid destination position
}
}
// Remove the source node from its current position
ListNode* srcNode = prevSrc->next;
prevSrc->next = srcNode->next;
// Insert the source node at the destination position
srcNode->next = prevDest->next;
prevDest->next = srcNode;
return head;
}
int main() {
int n;
cin >> n;
ListNode* head = new ListNode(-1);
for (int i = 0; i < n; i++) {
int val;
cin >> val;
insert(head, val);
}
printList(head); // Output original list
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int srcPos, destPos;
cin >> srcPos >> destPos;
ListNode* result = moveElements(head, srcPos, destPos);
if (result == NULL) {
cout << "error" << endl;
} else {
printList(result); // Output modified list
}
}
return 0;
}
希望对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问