ZBLOG

使用单链表来实现改变项目的顺序,要求使用头插法 先用C++实现含头结点的单链表,然后实现单链表中元素的插入。 注意不能改变每个结点包含的数据,必须通过修改指针来实现位置调换。 Input 第一行输入整数 n,表示链表中有n个数据; 第二行依次输入 n个数据,中间用空格分隔; 第三行输入整数t,表示插入的次数; 之后t行,每行两个数,分别为当前的位置和需要插到的位置。注意,位置编号从1开始。 下一次的插入基于上一次插入后的数据 Output 第一行,输出原始列表; 之后t行,输出每一次移动后...

下面是用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助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?