0
点赞
收藏
分享

微信扫一扫

【C++OJ_链表】单链表(类与构造)

seuleyang 2022-05-04 阅读 74
C++

【C++OJ_链表】单链表(类与构造)

题目描述

输入

输出

输入样例

输出样例

参考代码

#include <iostream>
using namespace std;

struct SNode
{
    int data;
    SNode *link;
    SNode(int d = 0, SNode *l = NULL) : data(d), link(l) {}
};

class CList
{
private:
    SNode *head;

public:
    CList(SNode * = NULL);
    void createList(int *value, int n);
    void printList();
    int insertNode(int pos, int value);
    int removeNode(int pos);
    ~CList(){}
};
CList::CList(SNode *h) : head(h)
{
}
void CList::createList(int *value, int n)
{
    while (--n >= 0)
    {
        head = new SNode(value[n], head);
    }
    printList();
}
void CList::printList()
{
    SNode *p;
    for (p = head; p->link != NULL; p = p->link)
    {
        cout << p->data << ' ';
    }
    cout << p->data << endl;
}
int CList::insertNode(int pos, int value)
{
    if (pos == 1)
    {
        SNode *p = new SNode(value, head->link);
        head->link = p;
        printList();
        return 0;
    }
    else
    {
        SNode *p = new SNode;
        SNode *r;
        r = head;
        p->data = value;
        pos--;
        while (pos--)
        {
            if (r->link != NULL)
                r = r->link;
            else
            {
                cout << "error\n";
                return 1;
            }
        }
        p->link = r->link;
        r->link = p;
        printList();
        return 0;
    }
}
int CList::removeNode(int pos)
{
    if (pos == 1)
    {
        SNode *p;
        p = head;
        head = head->link;
        delete p;
        printList();
        return 0;
    }
    else
    {
        SNode *p, *r;
        r = head;
        pos--;
        while (pos--)
        {
            p = r;
            if (r->link != NULL)
                r = r->link;
            else
            {
                cout << "error\n";
                return 1;
            }
        }
        p->link = r->link;
        delete r;
        printList();
        return 0;
    }
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        CList l;
        int tt;
        cin >> tt;
        int *value = new int[tt];
        int i;
        for (i = 0; i < tt; i++)
        {
            cin >> value[i];
        }
        l.createList(value, tt);
        int in;
        cin >> in;
        while (in--)
        {
            int pos, val;
            cin >> pos >> val;
            l.insertNode(pos, val);
        }
        int re;
        cin >> re;
        while (re--)
        {
            int pos;
            cin >> pos;
            l.removeNode(pos);
        }
    }
    return 0;
}
举报

相关推荐

0 条评论