【C++OJ_链表】单链表(类与构造)
题目描述
单链表节点的存储结构为:
struct SNode
{
int data;
SNode *next;
};
定义单链表类CList,数据成员有表头指针(SNode *head),成员函数有:
构造函数:初始化head.
createList(int *value, int n): 用value中的n个数据创建单链表.
printList(): 以head为表头依次输出每个节点的数据值。
insertNode(int pos, int value): 在单链表第pos个节点位置后插入新节点,数据为value。如插入不成功输出error。
removeNode(int pos): 删除第pos个节点,若删除不成功输出error。
析构函数:释放链表每个节点的堆内存。
输入
第一行:测试次数
每次测试格式为:
数据个数n 数据1 数据2 … 数据n
插入次数m
插入位置1 数据1
…
插入位置m 数据m
删除次数k
删除位置1
…
删除位置k
输出
每次测试产生的输出格式为:
输出创建链表后全部节点的数据
对每组插入测试数据:
输出插入操作后链表全部节点的数据
对每组删除测试数据:
输出删除操作后链表全部节点的数据
输入样例
2
5 2 3 5 7 3
2
1 40
7 60
2
7
3
6 1 2 10 0 1 5
2
1 40
7 60
2
1
3
输出样例
2 3 5 7 3
2 40 3 5 7 3
error
error
2 40 5 7 3
1 2 10 0 1 5
1 40 2 10 0 1 5
1 40 2 10 0 1 5 60
40 2 10 0 1 5 60
40 2 0 1 5 60
参考代码
#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;
}