c++单链表的基本操作

#include<iostream>
using namespace std;

class List
{
public:
List(){create_List();}
~List(){clear();}
void create_List();
//从链表尾部插入一个节点
void add(const int &d);
//从头插入一个节点
void insert(const int &d);
//在指定位置插入节点
void insert_pos(const int &n,const int &d);
//删除指定数据的节点
void erase(const int &d);
//删除指定位置的节点
void erase_pos(const int &n);
//修改指定数据
void updata(const int &d,const int &d1);
//修改指定位置的数据
void updata_pos(const int &n,const int &d);
//翻转链表函数
void reverse();
//打印
void print();
private:
struct Node
{
int data;
Node *next;
Node(const int &
data(d),next(NULL){}
};
Node *head;//创建头节点
//清理整个链表
void clear()
{
Node *p=head;
while(p)
{
Node *q=p->next;
delete p;
p=q;
}
}

//返回需要查找的指定节点的上一个节点,并返回
Node* find(const int &d)
{
Node *p=head;
for(;p;p=p->next)
{
if(p->next->data==d)
break;
}
return p;
}

};

//创建一个链表
void List::create_List()
{
head=new Node(0);
}

//从尾部插入
void List::add(const int &d)
{
Node *p=head;
Node *q=new Node(d);
while(p->next)
{
p=p->next;
}
p->next=q;
}

//从头部插入
void List::insert(const int &d)
{
Node *p=new Node(d);
p->next=head->next;
head->next=p;
}

//在指定位置插入节点
void List::insert_pos(const int &n,const int &d)
{
Node *p=head;
Node *q=new Node(d);
for(int i=1;i<n;i++)
{
p=p->next;
}
q->next=p->next;
p->next=q;
}

//删除指定数据的节点
void List::erase(const int &d)
{
Node *p=find(d);
Node *q=p->next;
p->next=p->next->next;
delete q;
}

//删除指定位置的节点
void List::erase_pos(const int &n)
{
Node *p=head;
for(int i=1;i<n;i++)
{
p=p->next;
}
Node *q=p->next;
p->next=p->next->next;
delete q;
}

//修改指定数据
void List::updata(const int &d,const int &d1)
{
Node *p=find(d);
p->next->data=d1;
}

void List::updata_pos(const int &n,const int &d)
{
Node *p=head;
for(int i=1;i<n;i++)
{
p=p->next;
}
p->next->data=d;
}
//打印链表
void List::print()
{

for(Node *p=head->next;p;p=p->next)
{
cout << p->data <<" ";
}
cout<<endl;
}
int main(int argc, const char * argv[])
{
List list;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.print();
cout<<endl;
cout<<".......插入10作为链表的第3个节点..........";
list.insert_pos(3,10);
cout<<endl;
list.print();
cout<<"........删除链表的第2个节点...............";
list.erase_pos(2);
cout<<endl;
list.print();
cout<<"........删除链表中指定数据为6的节点...............";
list.erase(6);
cout<<endl;
list.print();
cout<<"..........将链表中数据为8的节点改为88..............";
list.updata(8,88);
cout<<endl;
list.print();
cout<<"..........将链表中第4个节点的数据改为14..............";
list.updata(4,14);
cout<<endl;
list.print();
return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiangrikuidemaimai/p/11442100.html