链表的基本使用

来源:互联网 发布:淘宝审核部门电话 编辑:程序博客网 时间:2024/05/22 13:16

链表的基本使用

创建链表,添加元素,删除元素


#include "iostream"using namespace std;struct node{    int data;    node *next;};class list{    node *head;public:    list()    {        head=NULL;    }    void insertlist(int a,int b);    void deletelist(int a);    void outputlist();    node* gethead()    {        return head;    }};void list::outputlist(){    node *p=head;    while (p!=NULL)    {        cout<<p->data<<" ";        p=p->next;    }}void list::insertlist(int a,int b){    node *q,*p,*s;    s=new(node);    s->data=b;    p=head;    if (head==NULL)    {        head=s;        s->next=NULL;    }    else if (p->data==a)    {        s->next=p;        head=s;    }    else    {        while (p->data!=a && p->next!=NULL)        {            q=p;            p=p->next;        }        if (p->data==a)        {            q->next=s;            s->next=p;        }        else        {            p->next=s;            s->next=NULL;        }    }}void list::deletelist(int a){    node *p,*q;    p=head;    if (p==NULL)        return ;    if (p->data==a)    {        head=head->next;        delete p;    }    else    {        while (p->data!=a && p->next!=NULL)        {            q=p;            p=p->next;        }        if (p->data==a)        {            q->next=p->next;            delete p;        }    }}int main(){    list A,B;    int x,n;    cout<<"输入将要插入链表A的数字个数:";    cin>>n;    cout<<"输入"<<n<<"个数字:";    while (n--)    {        cin>>x;        A.insertlist(0,x);    }    cout<<"链表A:";    A.outputlist();    cout<<"\n输入要删除的数字:";    cin>>x;    A.deletelist(x);    cout<<"链表A:";    A.outputlist();    return 0;}


0 0
原创粉丝点击