题目描述
单链表节点的存储结构为:
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
输入样例1
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
输出样例1
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 *next;
};
class Clist
{
private:
SNode *head;
int length;
public:
Clist()
{
head = new SNode;
length = 0;
}
int Getlen() {return length;}
void creatList(int *value, int n)
{
SNode *p = head;
for(int i = 0;i < n;i ++)
{
SNode *q = new SNode;
q -> data = value[i];
q -> next = p -> next;
p -> next = q;
p = p -> next;
length ++;
}
}
void insertNode(int pos, int value)
{
SNode *p = head;
while(-- pos) p = p -> next;
SNode *q = new SNode;
q -> data = value;
q -> next = p -> next;
p -> next = q;
length ++;
}
void removeNode(int pos)
{
SNode *p = head;
while(-- pos) p = p -> next;
SNode *q = p -> next;
p -> next = q -> next;
delete q;
length --;
}
void printList()
{
SNode *p = head -> next;
while(p)
{
if(p != head -> next) cout << " ";
cout << p -> data;
p = p-> next;
}
cout << endl;
}
~Clist()
{
SNode *p = head;
while(p)
{
head = p;
p = p -> next;
delete head;
}
length = 0;
}
};
int main()
{
int t;
cin >> t;
while(t --)
{
Clist mylist;
int num;
cin >> num;
int *value = new int[num];
for(int i = 0;i < num;i ++) cin >> value[i];
mylist.creatList(value, num);
mylist.printList();
int m;
cin >> m;
while(m --)
{
int pos, number;
cin >> pos >> number;
pos ++;
if(pos >= 1 && pos <= mylist.Getlen() + 1)
{
mylist.insertNode(pos,number);
mylist.printList();
}
else cout << "error" << endl;
}
int k;
cin >> k;
while(k --)
{
int pos;
cin >> pos;
if(pos >= 1 && pos <= mylist.Getlen())
{
mylist.removeNode(pos);
mylist.printList();
}
else cout << "error" << endl;
}
delete []value;
}
return 0;
}