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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?