C++ linklist

来源:互联网 发布:国密算法sm2证书制作 编辑:程序博客网 时间:2024/06/05 12:46

I've read lots of lists' source codes before on the Internet or books.BUT I never code a list by myself .This time I made a try,the content and function is simple,but the structure is clear.At least it can convince myself.Of course I got some trouble during coding,but I solved them one by one finally.It's a valuable learning experience for me.

#include <string>#include <stdlib.h>#include <iostream>using namespace std; class Node//student's personal information{public:Node( string _name="noname",  char _sex='F', int _studentnum=0, double _score=0.0):name(_name),sex(_sex),studentnum(_studentnum),score(_score){}friend class List;private:string name;char sex;int studentnum;        double score;        Node *next;    };class List{public:    List(){createList();}    ~List(){clear();cout<<"clear list"<<endl;}    void createList();//creat a head pointer node    void insert(Node *&p);//insert a node    void insertpos(Node *&p,Node *&q);//insert a node to proper position    void cut(Node *&p);//delete a appointed node    void modify(Node *&p,Node *&q);//modify information    void print();//show list    void clear();    Node* find(int d);     Node * head;};void List::createList(){    head = new Node;    head->next=NULL;}void List::insert(Node *&p){    p->next = head->next;    head->next = p;}void List::print(){    for(Node * p = head->next;p;p=p->next){        cout << p->name<<"  "<<p->sex<<"  "<<p->studentnum<<"  "<<p->score<<"  " << endl;    }}void List::insertpos( Node *&p,Node *&q)//find by studentnum{    Node * k = find(p->next->studentnum);    q->next = k->next;    k->next = q;}void List::cut(Node *&p){    Node *k = find(p->next->studentnum);//use k to contain the node before p    Node *q = k->next;    p->next = k->next->next;    delete q;}void List::modify(Node *&p,Node *&q){    Node *k = find(p->studentnum);    k->next=q;}void List::clear(){        Node * p = head;        //circle to delete all        while(p){            Node * q = p->next;            delete p;            p = q;        }    }    Node *List::find(int d){        Node * p = head;        for(;p;p=p->next){            if(p->next->studentnum==d)                break;        }        return p;    }int main(){    List list;    Node *p1,*p2 ,*p3 ;    p1=new Node("Merry",'F',1,90.5);    p2=new Node("Jack",'M',2,93.0);    p3=new Node("Rose",'F',3,98.5);    list.insert(p3);    list.insert(p2);    list.insert(p1);cout<<"show list"<<endl; list.print();    cout << "---------------------" << endl;    cout<<"insert a node"<<endl;     Node *p4;    p4=new Node("Amy",'F',0,100.0);    list.insertpos(p2, p4);list.print();    cout << "---------------------" << endl;    cout<<"delete a node"<<endl;    list.cut(p2);    list.print();    cout << "---------------------" << endl;    cout<<"modify a node"<<endl;//modify studentnum    Node *p5;    p5=new Node("Nick",'M',5,85.5);list.modify(p3,p5);    list.print();    return 0;}

原创粉丝点击