链表的插入操作
来源:互联网 发布: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
- 链表的插入操作
- 链表的插入操作
- 链表的创建、插入、删除操作
- 链表的创建、插入、删除操作
- 链表的插入操作总结
- 静态链表的插入操作
- 链表插入删除操作
- 链表的插入操作及链表的倒置
- pta_链表_递增的整数序列链表的插入_(插入创建操作)
- 再论循环链表的插入和删除操作
- 链表的结点插入,删除等操作
- 链表的插入,删除,逆置操作...
- 单向链表的操作:创建,删除,插入,销毁,查找
- 链表的建立,插入,逆置,测长操作
- 10实现有序双向循环链表的插入操作
- 动态链表的删除 插入 查找操作
- 双向循环链表的创建,插入,删除操作
- 双向循环链表的创建修改插入删除操作
- 明天你好
- 融合架构
- Linux下tomcat的安装启动及停止
- 算法之排序-----排序第三篇 选择排序
- 不敢惹相思
- 链表的插入操作
- 关于linux下库的知识
- 雨 问
- java程序打包
- Eclipse快捷键大全(转载)
- Cracking the coding interview: 查找文中两个单词的距离
- .net / MySQLHelper
- HTML页面嵌入视频和JS控制切换视频
- APACHE服务器httpd.exe进程占用cpu100%的解决方法