ZBLOG

修改此代码在发现输入位置不合法输出"error"后不再打印移动后的结果 #include using namespace std; // 定义链表节点结构体 struct ListNode { int data; ListNode* next; }; // 创建链表 ListNode* createList(int n) { ListNode* head = new ListNode(); ListNode* cur = head;...

#include using namespace std;

// 定义链表节点结构体 struct ListNode {

int data;
ListNode* next;

};

// 创建链表 ListNode* createList(int n) {

ListNode* head = new ListNode();
ListNode* cur = head;

for (int i = 0; i < n; i++) {
    int num;
    cin >> num;

    ListNode* newNode = new ListNode();
    newNode->data = num;
    newNode->next = nullptr;

    cur->next = newNode;
    cur = cur->next;
}

return head;

}

// 打印链表 void printList(ListNode* head) {

if (head == nullptr || head->next == nullptr) {
    return;
}

ListNode* cur = head->next;

while (cur != nullptr) {
    cout << cur->data << " ";
    cur = cur->next;
}

cout << endl;

}

// 移动元素位置 bool moveElement(ListNode* head, int currentPos, int targetPos) {

if (currentPos == targetPos || head == nullptr || head->next == nullptr) {
    return false;
}

// 获取待移动的节点和其前一个节点
ListNode* prevNode1 = nullptr; // 待移动节点的前一个节点
ListNode* currentNode1 = head; // 待移动节点

 while (currentNode1 != nullptr && currentPos > 0) {
     prevNode1 = currentNode1;
     currentNode1 = currentNode1->next;
     currentPos--;
 }

 if (currentNode1 == nullptr) { 
     cout << "error" << endl; 
     return false; 
 }

 ListNode* prevNode2 = nullptr; // 目标位置节点的前一个节点
 ListNode* currentNode2 = head; // 目标位置节点

 while (currentNode2 != nullptr && targetPos > 0) {
     prevNode2 = currentNode2;
     currentNode2 = currentNode2->next;
     targetPos--;
 }

 if (currentNode2 == nullptr) { 
     cout << "error" << endl; 
     return false; 
 }

// 移动节点
if (prevNode1 != nullptr) {
    prevNode1->next = currentNode1->next;
}

if (prevNode2 != nullptr) {
    prevNode2->next = currentNode1;
} else {
    head->next = currentNode1;
}

currentNode1->next = currentNode2;

return true;

}

int main() {

int n, t;
cin >> n;

ListNode* head = createList(n);
printList(head);

cin >> t;

for (int i = 0; i < t; i++) {

   int currentPos, targetPos;
   cin >> currentPos >> targetPos;

   if(moveElement(head, currentPos, targetPos)){
       printList(head);
   }

}

return 0; }


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9336

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?