“classnode.hpp”:
#define _CRT_SECURE_NO_WARNINGS 1
#include <string>
#include <ctime>
#include <iostream>
using namespace std;
class Node
{
friend class Linklist;
public:
Node();
Node(int data);
Node(Node* old);
private:
int data;
Node* next;
};
Node::Node()
{
this->data = 0;
this->next = NULL;
}
Node::Node(int data)
{
this->data = data;
this->next - NULL;
}
Node::Node(Node* old)
{
this->data = rand() % 10;
this->next = old;
}
class Linklist
{
public:
//初始化
Linklist();
Linklist(Node* first);
void InitList(int len);
void HeadInsert_Init();
void printlist();
Node& search_from_i(int i);
Node& search_elem(int elem_data);
void Insert_after_pre(Node*p,Node* pre);
Node& delete_after_pre(Node* pre);
private:
Node* first;
friend class Node;
int length=0;
};
Linklist::Linklist()
{
}
Linklist::Linklist(Node* first)
{
this->first = first;
}
void Linklist::HeadInsert_Init()
{
Node* n = new Node(this->first->next);
this->first->next = n;
this->length++;
}
void Linklist::InitList(int len)//头插法建立单链表
{
for (int i = 0; i < len; i++)
{
this->HeadInsert_Init();//在同一个函数内部无法在循环内对同一个变量初始化不同的存储空间
//我们采取封装函数,让循环体中变量作为另一个函数的局部变量出现,就可以实现以上需求
}
}
void Linklist::printlist()
{
Node* p = this->first->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << "当前表长为:" << this->length << endl;
}
Node& Linklist::search_from_i(int i)
{
Node* p(this->first);
while (i != 0)
{
if (p == NULL)
{
cout << "链表不存在第" << i << "个结点";
return *p;
}
p = p->next;
i--;
}
return *p;
}
Node& Linklist::search_elem(int elem_data)
{
Node* p = this->first->next;
int num = 1;
while (p != NULL)
{
if (p->data == elem_data)
{
cout << "第一个值为" << elem_data << "的结点在第" << num << "个位置上" << endl;
return *p;
}
p = p->next;
num++;
}
cout << "没有值为" << elem_data << "的结点" << endl;
return *p;
}
void Linklist::Insert_after_pre(Node* p,Node* pre)
{
//Node* n=new Node(pre->next);
p->next = pre->next;
pre->next =p;
this->length++;
}
Node& Linklist::delete_after_pre(Node* pre)
{
Node* p = pre->next;
pre->next = pre->next->next;
this->length--;
return *p;
}
源文件:
#define _CRT_SECURE_NO_WARNINGS 1
#include "classnode.hpp"
int main()
{
srand((unsigned)time(NULL));
Linklist L(new Node());//定义一个带头节点的单链表,
int len;
cout << "请输入您定义的单链表长度:";
cin >> len;
L.InitList(len);
L.printlist();
Node n(3);//定义一个data域为3的Node结点
L.Insert_after_pre(&n,&L.search_from_i(3));//在线性表的3位置之后插入结点n
L.printlist();
L.delete_after_pre(&L.search_from_i(3));//删除线性表的3位置后的结点
L.printlist();
L.search_elem(3);//查找链表中第一个3出现的位置
system("pause");
return 0;
}
实验结果: