题目描述
单链表结点的存储结构SNode包含两部分:数据、下一结点指针。单链表首个结点的地址head为表头指针,定义SNode *head=NULL表示单链表初始为空。
单链表的创建:createList(SNode *&head, int *value, int n),用value数组中的n个数据生成一个单链表(表头指针为head)。
单链表的输出:printList(SNode *head),从头至尾遍历以head为表头的单链表,输出每个结点的数据值。
单链表数据插入: insertNode(SNode *head, int pos, int value),在单链表第pos(1<=pos<=L+1)个结点位置插入新结点,数据为value。若插入不成功,输出error。
单链表数据删除: removeNode(SNode *head, int pos), 删除单链表第pos(1<=pos<=L)个结点。若删除不成功,输出error。
单链表的撤销:deleteList(SNode *head),删除以head为表头的单链表,即释放链表每个结点的堆内存。
注:不可以用任何形式的数组来实现链表,否则不计成绩。
输入
第一行:测试次数t
对每组测试数据,格式如下:
数据个数n 数据1 数据2 数据3 ... 数据n
插入次数m
插入位置1 数据1
...
插入位置m 数据m
删除次数o
删除位置1
...
删除位置o
输出
对每组测试数据:
输出创建链表后链表中全部结点的数据
对每组插入测试数据:
输出插入操作后链表中全部结点的数据
对每组删除测试数据:
输出删除操作后链表中全部结点的数据
样例
输入:
2
5 2 3 5 7 3
2
2 40
8 60
2
7
3
6 1 2 10 0 1 5
2
2 40
8 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* next;
};
void createList(SNode*& head, int* value, int n);
void printList(SNode* head);
int insertNode(SNode* head, int pos, int value);
int removeNode(SNode* head, int pos);
void deleteList(SNode* head);
int main()//主函数
{
int t,i;
int a[200], n, m1, pos1, value, m2, pos2,k;
cin >> t;
while (t--) {
SNode* head = new SNode;
//head = NULL;
head->data = 0;
head->next = NULL;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
createList(head,a,n);
printList(head);
cin >> m1;
for (i = 1; i <= m1; i++)
{
cin >> pos1 >> value;
k=insertNode(head, pos1, value);
if (k == 1)printList(head);
else cout << "error" << endl;
}
cin >> m2;
for (i = 1; i <= m2; i++)
{
cin >> pos2;
k = removeNode(head, pos2);
if(k==1)printList(head);
else cout << "error" << endl;
}
deleteList(head);
}
return 0;
}
void createList(SNode*& head, int* value, int n)
{
int i;
head->data = n;
SNode* p = new SNode;
p = head;
for (i = 0; i < n; i++)
{
SNode* q = new SNode;
q->data = *(value + i);
q->next=NULL;
p->next = q;
p = p->next;
}
}
void printList(SNode* head)
{
int i;
SNode* p = head;
for (i = 1; i <head->data; i++)
{
p = p->next;
cout << p->data << " ";
}
p = p->next;
cout <<p->data<< endl;
}
int insertNode(SNode* head, int pos, int value)
{
int i;
SNode* p = new SNode;
p = head->next;
if (pos >= 1 && pos <= head->data + 1) {
for (i = 1; i < pos-1; i++)
{
p = p->next;
}
SNode* q = new SNode;
q->next = p->next;
q->data = value;
p->next = q;
head->data++;
return 1;
}
else {
return 0;
}
}
int removeNode(SNode* head, int pos)
{
int i;
if (pos >= 1 && pos <= head->data) {
SNode* p = head;
for (i = 1; i <pos; i++)
p = p->next;
SNode* q = new SNode;
q = p->next;
p->next = q->next;
head->data--;
return 1;
}
else{
return 0;
}
}
void deleteList(SNode* head)
{
while (head->next != NULL)
{ SNode* p = new SNode;
p = head->next;
head->next = p->next;
delete p;
}
delete head;
}
ps:本题是由结构体到链表的过渡,对于初学链表掌握结构有一些帮助