链表

本博客挑战读者独立构建链表并实现插入元素及遍历功能。内容包括输入输出格式说明,以及样例输入输出展示。要求程序在给定输入数据下,能正确处理插入操作并输出相应结果。

  •  1000ms
  •  32768K

现在,需要你独立的去构造一个链表,并实现向其中插入元素以及遍历链表的功能。通过前面的学习,你已经能够独立完成这些代码了吧,在这里我们就不再给出提示了。

代码框架已经写好了,你只需要在对应的位置去补全代码。我们在测试时,会给出几组输入数据,一旦你的程序所得到的输出数据和我们标准的输出一致,就认为你通过了这道题。

输入格式

第一行输入是一个整数 nn1 \leq n \leq 1001n100),表示一共要执行 nn 次插入操作。

接下来输入 nn 行,每行输入两个整数 pp 和 qq0 \leq p,q \leq 1000p,q100),其中 pp 表示结点插入链表中的位置(从下标为 00 开始),qq 表示插入元素的值,两个整数之间用一个空格隔开。

输出格式

输出一共 n + 1n+1 行。前 nn 行对应每次插入操作,一行一个结果,如果一个元素成功插入到了链表中,请输出success,如果插入失败则输出failed

第 n + 1n+1 行输出最后的链表,每两个整数之间用一个空格隔开。

样例输入
6
2 3
0 4
1 3
3 2
0 1
2 2
样例输出
failed
success
success
failed
success
success
1 4 2 3

#include <iostream>
#include<iostream>
using namespace std;

template <typename Type> class Node {
public:
    Type data;
    Node<Type>* next;
    Node(const Type &_data){
        data = _data;
        next = NULL;
    }
};
template <typename Type> class LinkedList {
private:
    Node<Type>* head;
public:
    LinkedList() {
        head = NULL;
    }
    ~LinkedList() {
        Node<Type> *current_node = head;
        while(current_node!=NULL){
            Node<Type> *delete_node = current_node;
            current_node = current_node->next;
            delete delete_node;
        }
    }
    bool insert(Node<Type> *node,int index) {
        if (head == NULL) {
            if (index != 0) {
                cout << "failed" <<endl;
                return false;
            }
            head = node;
            cout << "success" <<endl;
            return true;
        }
        if (index == 0) {
            node->next = head;
            head = node;
            cout << "success" <<endl;
            return true;
        }
        Node<Type> *current_node = head;
        int count = 0;
        while (current_node->next != NULL && count < index - 1) {
            current_node = current_node->next;
            count++;
        }
        if (count == index - 1) {
            node->next = current_node->next;
            current_node->next = node;
            cout << "success" <<endl;
            return true;
        }
        cout << "failed" <<endl;
        return false;
    }
    void output() {
        if(head==NULL) {return;}
        Node<Type>* current_node = head;
        while(current_node!=NULL){
            if(current_node != head) cout << " ";
            cout << current_node->data;
            current_node = current_node->next;
        }
        cout << endl;
    }
};
int main() {
    LinkedList<int> linkedlist;
    int n,p,q;
    cin >> n;
    for(int i=0;i<n;i++){
        cin >> p >> q;
        Node<int>* node = new Node<int>(q);
        linkedlist.insert(node,p);
    }
    linkedlist.output();
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值