ZBLOG

修改此代码:在发现某次移动时,输入的位置不合法,直接输出"error"并且该次不打印移动后的结果,直接跳过 #include using namespace std; // 定义链表节点结构体 struct ListNode { int data; ListNode* next; }; // 创建链表 ListNode* createList(int n) { ListNode* head = new ListNode(); Lis...

以下是修改后的代码:

#include <iostream>
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;
}

// 移动元素位置
void moveElement(ListNode* head, int currentPos, int targetPos) {
    if (currentPos == targetPos || head == nullptr || head->next == nullptr) {
        return;
    }

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

     while (currentNode1 != nullptr && currentPos > 0) {
         prevNode1 = currentNode1;
         currentNode1 = currentNode1->next;
         currentPos--;
     }
 
     if (currentNode1 == nullptr) {
         cout << "error" << endl; 
         return;  // 出现错误,直接返回
     }
 
     ListNode* prevNode2 = nullptr; // 目标位置节点的前一个节点
     ListNode* currentNode2 = head; // 目标位置节点
 
     while (currentNode2 != nullptr && targetPos > 0) {
         prevNode2 = currentNode2;
         currentNode2 = currentNode2->next;
         targetPos--;
     }
 
     if (currentNode2 == nullptr) {
         cout << "error" << endl;
         return;  // 出现错误,直接返回
     }

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

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

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;

        moveElement(head, currentPos, targetPos);

        printList(head);
    }

   return 0;
}

修改后的代码会在发现移动位置不合法时输出”error”,并且跳过打印移动后的结果。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?