题目描述
用C++语言和类实现单链表,含头结点
属性包括:data数据域、next指针域
操作包括:插入、删除、查找
注意:单链表不是数组,所以位置从1开始对应首结点,头结点不放数据
输入
n
第1行先输入n表示有n个数据,接着输入n个数据
第2行输入要插入的位置和新数据
第3行输入要插入的位置和新数据
第4行输入要删除的位置
第5行输入要删除的位置
第6行输入要查找的位置
第7行输入要查找的位置
输出
第1行输出创建后的单链表的数据
每成功执行一次操作(插入或删除),输出执行后的单链表数据
每成功执行一次查找,输出查找到的数据
如果执行操作失败(包括插入、删除、查找等失败),输出字符串error,不必输出单链表
输入样例1
6 11 22 33 44 55 66
3 777
1 888
1
11
0
5
输出样例1
11 22 33 44 55 66
11 22 777 33 44 55 66
888 11 22 777 33 44 55 66
11 22 777 33 44 55 66
error
error
44
#include <iostream>
using namespace std;
class LNode
{
public:
int data;
LNode* next;
LNode()
{
next = nullptr;
}
};
class LinkList
{
private:
LNode* head;
int len;
public:
LinkList()
{
head = new LNode;
len = 0;
}
void Create()
{
int n;
cin >> n;
LNode* tail = head;
for (int i = 0; i < n; i++)
{
int data;
cin >> data;
LNode* t = new LNode;
t->data = data;
tail->next = t;
tail = t;
len++;
}
Display();
}
LNode* GetElem(int i)
{
if (i<0 || i>len)
return nullptr;
LNode* p = head;
for (int k = 0; k < i; k++)
{
p = p->next;
}
return p;
}
void Insert(int i, int e)
{
if (i<1 || i>len + 1)
{
cout << "error" << endl;
return;
}
LNode* p = GetElem(i - 1);
LNode* t = new LNode;
t->data = e;
t->next = p->next;
p->next = t;
len++;
Display();
}
void Delete(int i)
{
if (i<1 || i>len)
{
cout << "error" << endl;
return;
}
LNode* p = GetElem(i - 1);
LNode* q = p->next;
p->next = q->next;
delete q;
len--;
Display();
}
void Find(int i)
{
if (i<1 || i>len)
{
cout << "error" << endl;
return;
}
LNode* p = GetElem(i);
cout << p->data << endl;
}
void Display()
{
LNode* p = head->next;
for (int i = 0; i < len; i++)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
};
int main()
{
LinkList ll;
ll.Create();
int i, e;
cin >> i >> e;
ll.Insert(i, e);
cin >> i >> e;
ll.Insert(i, e);
cin >> i;
ll.Delete(i);
cin >> i;
ll.Delete(i);
cin >> i;
ll.Find(i);
cin >> i;
ll.Find(i);
return 0;
}
该文描述了如何使用C++编程语言通过类来实现单链表,包含头结点,数据域和指针域。类提供了插入、删除和查找等操作,并给出了示例输入和输出,说明了链表的位置从1开始计数,头结点不存放数据。
1192

被折叠的 条评论
为什么被折叠?



