单向链表综合实例(建立,删除,查找)
2012-09-11 18:07
585 查看
单向链表综合实例
#include<iostream.h> #include<conio.h> struct node { int data; node *next; }; node *insertdata(int n,node *head); node *deletedata(int n,node *head); node *finddata(int n,node *head); void outputlist(node *head); int main() { int n; int num; node *listhead=NULL; cout<<"请输入节点数 "; cin>>n; cout<<"请输入"<<n<<"个整数: "; for(int i=0;i<n;i++) { cin>>num; //将num按照从小到大的顺序插入链表中 listhead=insertdata(num,listhead); } outputlist(listhead); cout<<"\n请输入需要查找的数: "; cin>>num; finddata(num,listhead); //删除结点 cout<<"\n请输入想要删除的点: "; cin>>num; listhead=deletedata(num,listhead); //输出删除结点后的链表 outputlist(listhead); getch(); return 0; } //查找某数 node *finddata(int n,node *head) { node *curnode=head; while(curnode) { if(curnode->data==n) { //找到n cout<<"在列表中找到 "<<n<<endl; return curnode; } curnode=curnode->next; } //未找到n cout<<"没有找到 "<<n<<endl; return NULL; } //插入某数(将输入的整数按找从小到大的顺序插入到已经排好序的链表中) node *insertdata(int n,node *head) { node *curnode=head; node *prenode=NULL; node *newnode=NULL; //找到插入位置 while((curnode!=0)&&(curnode->data<n)) //如果n最小,不用进入循环,直接插到表头前面 { prenode=curnode; //在prenode后面插入结点 curnode=curnode->next; //在curnode前面插入结点 } newnode=new node; if(newnode==NULL) { cout<<"内存分配不成功 "; return head; } //内存分配成功 newnode->data=n; //插入位置为链表头,新建结点插入到链首结点之前 if(prenode==NULL) { newnode->next=head; return newnode; } else { prenode->next=newnode; newnode->next=curnode; return head; } } //删除结点 node *deletedata(int n,node *head) { node *curnode=head; node *prenode=NULL; if(head==NULL) //链表为空,直接返回 return NULL; while((curnode!=NULL)&&(curnode->data!=n)) { prenode=curnode; //prenode为要删除结点的前驱 curnode=curnode->next; //赋值符号左边的curnonde即为curnode->data==n时的结点指针 } //未找到n if(curnode==NULL) { cout<<"未在链表中找到 "<<n<<endl; return head; } //删除的点为链首结点 if(prenode==NULL) //等价于if(curnode==head) head=head->next; else prenode->next=curnode->next; delete curnode; return head; } //输出列表 void outputlist(node *head) { cout<<"List:"; node *curnode=head; while(curnode) { cout<<curnode->data; if(curnode->next) cout<<"->"; curnode=curnode->next; } cout<<endl; }
相关文章推荐
- 单向链表的建立、打印、查找、插入、删除
- 链表建立输出删除插入的综合实例
- 双链表的初始化,建立,插入,查找,删除。
- 链表建立,插入,查找,删除,归并
- 单向链表的建立、打印、 删除
- 数据结构作业代码保存-2.1 单向循环链表的建立,插入和删除,和指针移动
- 单链表的初始化,建立,插入,查找,删除
- 双链表的初始化,建立,插入,查找,删除
- 双链表( 初始化,建立,插入,查找,删除 )
- C语言:动态链表的建立,查找,删除,插入功能的实现
- 单链表的初始化,建立,插入,查找,删除
- 单向链表的创建、遍历、求长、判存、判空、插入、删除、查找(按位置或元素)、合并
- 单向链表-查找和删除
- 单链表的建立,查找,插入,删除,测长,打印,逆置操作实现
- 单向链表的操作:创建,删除,插入,销毁,查找
- 单链表的建立,测长度,打印,删除,插入,逆置c++代码实例及运行结果
- 单链表建立,插入,删除,查找,遍历操作
- 单链表的初始化,建立,插入,查找,删除
- 链表的基本操作(C语言版):建立,插入,删除,查找,输出
- 单链表的建立,测长度,打印,删除,插入,逆置c++代码实例及运行结果