码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List

时间:2020-03-21 09:52:22      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:int   null   while   lag   ras   else   lin   pre   ase   

#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;
}

Linked List

标签:int   null   while   lag   ras   else   lin   pre   ase   

原文地址:https://www.cnblogs.com/XPHouse/p/12536316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!