链表的插入操作

来源:互联网 发布:bat批处理卸载软件 编辑:程序博客网 时间:2024/05/01 11:01
 链表的插入操作
#include<iostream>#include<string>#include<cstring>using namespace std;struct Computer{int CNumber;string CName;double CPrice;Computer()                            //默认的构造函数{   CNumber=0;   CName="";   CPrice=0.0;}Computer(int num,string name,double price){ CNumber=num; CName=name; CPrice=price;}Computer(Computer&computer){   this->CNumber=computer.CNumber;   this->CName=computer.CName;   this->CPrice=computer.CPrice;}Computer&operator=(Computer&computer){                if(this==&computer)                return *this;           this->CNumber=computer.CNumber;   this->CName=computer.CName;   this->CPrice=computer.CPrice;   return *this;}};class CLinkedList{public:struct Node{Computer data;Node *next;};private:Node *head;int length;public:CLinkedList();  //无参构造函数,建立只有头节点的空链表~CLinkedList();  //析构函数void Insert(int i,Computer c);  //插入操作,在第i个位置插入元素值为x的节点void Delete(int i);  //删除操作,在单链表中删除第i个节点int Length(){return length;};  //求单链表的长度//void nixu(); //链表的逆序};CLinkedList::CLinkedList():length(0),head(NULL){}CLinkedList::~ CLinkedList (  ){    Node* p = NULL;    while( head )    {        p = head;        head = p->next;        delete p;        p = NULL;    }    //return;}void CLinkedList::Insert(int i,Computer c){    Node*p=head;    if(length==0&&i!=0)                    // 如果是空的话第一个插入的节点必须是 i=0    {         cout<<"the first ,i must be 0"<<endl;         return;    }   else if(p==NULL&&i==0)    {       p=new Node();       p->data=c;       head=p;                             //这个太重要了,想想为什么       length++;       return ;    }    else if(i>=length)                     //插入越界判断       {         cout<<"the i is langer than "<<length<<" !"<<endl;         return ;       }    else {         if(i==0)                          //要是在head的位置进行插入的话必须要这么处理下         {         Node *temp=new Node();         temp->data=c;         temp->next=head;         head=temp;         length++;         }         else{          for(int j=0;j<i-1;j++)          {           p=p->next;          }          Node *temp=new Node();          temp->data=c;          temp->next=p->next;          p->next=temp;          length++;         }        }}void CLinkedList::Delete(int i){Node *p=head;int count=0;while(p!=NULL&&count<i-1){p=p->next;count++;}if(p==NULL||p->next==NULL)throw"位置异常";else{Node *q=new Node;q=p->next;p->data=q->data;p->next=q->next;delete q;}}int main(){    Computer p1,p2,p3;    CLinkedList  listt;    listt.Insert(1,p3);    listt.Insert(2,p1);    listt.Insert(0,p2);    listt.Insert(0,p2);    listt.Insert(0,p2);    listt.Insert(2,p3);    listt.Insert(3,p3);    cout<<listt.Length();    return 0;}


0 0
原创粉丝点击