单向链表插入新节点
2017-09-20 18:28
267 查看
#include <iostream> #include <cstdlib> #include <ctime> #include <string.h> #include <iomanip> //操作符的头文件 using namespace std; class list { public: int num,score; char name[10]; class list *next; }; typedef class list node; typedef node *link; link findnode(link head,int num) { link ptr; ptr=head; while(ptr!=NULL) { if(ptr->num==num) return ptr; ptr=ptr->next; } return ptr; } link insertnode(link head,link ptr,int num,int score,char name[10]) { link InsertNode; InsertNode=new node; if(!InsertNode) return NULL; InsertNode->num=num; InsertNode->score=score; strcpy(InsertNode->name,name); InsertNode->next=NULL; if(ptr==NULL) //插入第一个节点 { InsertNode->next=head; return InsertNode; } else { if(ptr->next==NULL)//插入最后一个节点 { ptr->next=InsertNode; } else //插入中间节点 { InsertNode->next=ptr->next; ptr->next=InsertNode; } } return head; } int main() { link head,ptr,newnode; int new_num, new_score; char new_name[10]; int i,j,position=0,data[12][2]; char namedata[12][10]={{"Allen"},{"Scott"},{"Marry"}, {"John"},{"Mark"},{"Ricky"},{"Lisa"},{"Jasica"}, {"Hanson"},{"Amy"},{"Bob"},{"Jack"}}; srand((unsigned)time(NULL)); cout<<"座号 成绩 座号 成绩 座号 成绩 座号 成绩"<<endl; cout<<"=============================================="<<endl; for(i=0;i<12;i++) { data[i][0]=i+1; data[i][1]=rand()%50+51; } for(i=0;i<3;i++) { for (j=0;j<4;j++) cout<<"["<<data[j*3+i][0]<<"] ["<<data[j*3+i][1]<<"] "; cout<<endl; } head=new node; //建立链表头指针 if(!head) { cout<<"Error!! 内存分配失败!!"<<endl; exit(1); } head->num=data[0][0]; for (j=0;j<10;j++) head->name[j]=namedata[0][j]; head->score=data[0][1]; head->next=NULL; ptr=head; for(i=1;i<12;i++) //建立链表 { newnode=(link)malloc(sizeof(node)); newnode->num=data[i][0]; for (j=0;j<10;j++) newnode->name[j]=namedata[i][j]; newnode->score=data[i][1]; newnode->next=NULL; ptr->next=newnode; ptr=ptr->next; } while(1) { cout<<"请输入要插入其后的学生编号,结束输入-1:"; cin>>position; if(position==-1)//循环中断条件 break; else { ptr=findnode(head,position); cout<<"请输入新插入的学生编号:"; cin>>new_num; cout<<"请输入新插入的学生成绩:"; cin>>new_score; cout<<"请输入新插入的学生姓名:"; cin>>new_name; head=insertnode(head,ptr,new_num,new_score,new_name); } } ptr=head; cout<<"\n\t座号\t 姓名\t成绩\n"; cout<<"\t==============================\n"; while(ptr!=NULL) { cout<<"\t["<<ptr->num<<"]\t[ "<<ptr->name<<"]"<<setw(6)<<"\t["<<ptr->score<<"]\n"; ptr=ptr->next; } delete head; system("pause"); return 0; }
相关文章推荐
- 华为机试题:向升序单向链表中插入一个节点
- 华为OJ 向升序单向链表中插入一个节点
- 求助 向升序单向链表中插入一个节点 求教程序中哪里错了?
- 向升序单向链表中插入一个节点
- 单向链表小练习--》创建链表头,添加删除链表节点,释放链表内存,选择插入数据
- 向升序单向链表中插入一个节点
- 单向链表(三) 在指定位置插入新的节点
- 向有序循环单向链表中插入节点
- 单向链表中,如何在给定节点前快速插入一个节点?
- [华为机试练习题]49.向升序单向链表中插入一个节点
- 单向链表中,如何在给定节点前快速插入一个节点?
- 单向链表的节点插入与删除
- 单向链表末尾插入一个节点(指向指针的指针该怎样理解)
- 单向链表之有序插入节点(C语言实现)
- 向升序单向链表中插入一个节点
- 单向链表中,如何在给定节点前快速插入一个节点?
- 只知道某个单向链表的中的某个指针,且该指针不是尾指针,如何删除该节点。
- OJ-------从单向链表中删除指定节点
- 单向链表的创建、遍历、求长、判存、判空、插入、删除、查找(按位置或元素)、合并
- 双向链表的初始化,建立,添加节点和删除节点(注意插入和删除要分三种情况)