c++单向链表

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
namespace mynode
{
    typedef int type;
    struct Node
        {
            type data;
            Node *next;
        };
    class node
    {
        Node*head;
    public:
        node();
        ~node();
        void append(type x);
        Node*find(type x);
        Node*at(int pos);
        bool dell(type x);
        bool Dell(int pos);
        void show();
        void insert(type x,int pos);
        void fill();

    };
    node::node(){
        head=new Node;
        head->next=NULL;
    }
    node::~node(){
        Node*p;
        while(head){
            p=head;
            head=head->next;
            delete p;
        }
    }
    void node::append(type x){
        Node*p=head;
        while(p->next)p=p->next;
        Node*t=new Node;
        t->data=x;
        t->next=NULL;
        p->next=t;
    }
    Node* node::find(type x){
        Node*p=head->next;
        while(p&&p->data!=x)
            p=p->next;
        return p;
    }
    Node*node::at(int pos){
        int i=0;
        Node*p=head->next;
        while(p&&i<pos){
            p=p->next;
            i++;
        }
        if(i==pos)
            return p;
        else return NULL;
    }
    void node::show(){
        Node*p=head->next;
        while(p){
            cout<<p->data<<" ";
            p=p->next;
        }
        cout<<endl;
    }
    void node::fill(){
        for(int i=0;i<10;i++)
            this->append(i*i+2*i+5);
    }
    bool node::dell(type x){
        Node*pre=head,*p=head->next;
        while(p&&p->data!=x){
            pre=p;
            p=p->next;
        }
        if(p){
            pre->next=p->next;
            delete p;
            return true;
        }
        else return false;
    }
    bool node::Dell(int pos){
        int i=0;
        Node*pre=head,*p=head->next;
        while(p&&i<pos){
            pre=p;
            p=p->next;
            i++;
        }
        if(p){
            pre->next=p->next;
            delete p;
            return true;
        }return false;
    }
    void node::insert(type x,int pos){
        int i=0;
        Node*pre=head,*p=head->next;
        while(p&&i<pos){
            pre=p;
            p=p->next;
            i++;
        }
        if(p){
            Node*t=new Node;
            t->data=x;
            t->next=p;
            pre->next=t;
        }
    }
}
int main()
{
    using namespace mynode;
    node one;
    one.fill();
    one.show();
    int i,j;
    while(cin>>i>>j){
        one.insert(i,j);
        one.show();
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Thereisnospon/p/4768499.html