Linked List

#include <iostream>
#include <string>

using namespace std;

struct Node
{
Node()
:value(0),
pNext(nullptr)
{}

int value;
Node* pNext;
};

class CLinkList
{
private:
Node* pHead;
public:
CLinkList()
:pHead(nullptr)
{}

void insert(int pos, int value)
{
if (pos == 0 && pHead == nullptr) {
Node* pNew = new Node();
pNew->value = value;
pHead = pNew;
return;
}

Node* pNode = pHead;
for (int i = 0; i < pos - 1; ++i) {
if (pNode != nullptr) {
pNode = pNode->pNext;
} else {
return;
}
}

Node* pNew = new Node();
pNew->value = value;
pNew->pNext = pNode->pNext;

pNode->pNext = pNew;
}

void erase(int pos)
{
Node* pfront = pHead;
Node* pNode = pHead;
for (int i = 0; i < pos - 1; ++i) {
if (i > 0) {
pfront = pfront->pNext;
}
if (pNode != nullptr) {
pNode = pNode->pNext;
} else {
return;
}
}

pfront->pNext = pNode->pNext;
}

void print()
{
Node * pNow = pHead;
while (pNow) {
cout << pNow->value << " ";
pNow = pNow->pNext;
}
}
};

int main ()
{
CLinkList list;
int n =0;
int q = 0;

cin >> n >> q;

for (int i = 0; i < n; ++i) {
int value;
cin >> value;
list.insert(i, value);
}

for (int i = 0; i < q; ++i) {
int flag = 0;
int pos = 0;
int value = 0;
cin >> flag;
if (flag == 1) {
cin >> pos >> value;
list.insert(pos, value);
} else if (flag == 2) {
cin >> pos;
list.erase(pos);
}
}
list.print();
return 0;
}
posted @ 2020-03-21 03:04  magongbianma  阅读(154)  评论(0编辑  收藏  举报