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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM