用c++实现的 数据域为int类型的 带头结点的 单向链表
基本操作:
- 构造函数
- 表尾增加数据
- 指定位置插入数据
- 查找具体位置输出数据
- 删除具体位置的数据
- 输出整个链表数据
- 逆置链表
- 析构函数
主函数里是对整个链表的测试
/*带头结点的单链表 c++ int*/
#include<iostream>
using namespace std;
struct Node{
int data;//数据域
Node *next;//指针域
};
class MyList{
Node*head;//头指针
Node*tail;//尾指针
public:
MyList(){
head=new Node;//头结点
tail=head;
head->next=NULL;//头结点指向空
}//构造函数
//链表尾部增加元素
void Myappend(int x){
tail->next=new Node;
tail=tail->next;
tail->next=NULL;
tail->data=x;
}
//指定位置插入
void Myinsert(int x,int y){
Node*p=head->next;//首结点
int n=1;//记录当前位置
while(n!=x-1){//让p指向想插入的前一个结点
if(p==NULL){
Myappend(y);
}
p=p->next;
n++;
}
Node*q=p->next;
p->next=new Node;
p=p->next;
p->next=q;
p->data=y;
}
//查找在第几个位置上的数据
bool MyFind(int x){
Node*p=head->next;//首结点
int n=1;//记录当前位置
while(n!=x){//让p指向想查找的结点
if(p==NULL){
cout<<"无此结点"<<endl;
return false;
}
p=p->next;
n++;
}
cout<<p->data<<endl;
return true;
}
//删除在第几个位置上的数据
bool MyDelete(int x){
Node*p=head->next;//首结点
int n=1;//记录当前位置
while(n!=x-1){//让p指向想删除的前一个结点
if(p==NULL){
cout<<"无此结点"<<endl;
return false;
}
p=p->next;
n++;
}
Node*q=p->next;
p->next=q->next;
delete q;
}
//输出数据
void Mycout(){
Node*p=head->next;//首结点
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//逆置
bool MyReverse(){
Node*p=head->next;//指向首结点
head->next=NULL;//头结点指向空
Node*q=p;
while(q!=NULL){
q=p->next; //保存下一个结点
p->next=head->next;//逆转指针
head->next=p;//头指针指向p
p=q;//移动p指针
}
}
//析构函数
~MyList(){
Node *p;
while(head->next!=NULL){
p=head->next;//用于保存下一个节点的地址
delete head;
head=p;
}
}
};
int main(){
MyList a;
a.Myappend(1);
a.Myappend(2);
a.Myappend(4);
a.Myinsert(3,3);
a.Myinsert(5,5);
a.Myinsert(6,6);
a.Mycout() ;
a.MyDelete(3);
a.MyReverse() ;
a.Mycout();
}
暂时就写这么多,后续可能会更新为有模板 和其他更多基本操作 和其他类型的 链表
谢谢阅览,欢迎提供意见,一起敲代码,加油!