编程实现双链表的建立、插入、删除、求长、逆置
2016-07-21 09:08
441 查看
#include <iostream> #include <stdio.h> #include <malloc.h> using namespace std; typedef struct node { int data; struct node *next; }node; node *creat(){//单链表创建 node *head,*p,*s; int x,cycle=1; head=(node *)malloc(sizeof(node)); p=head; while(cycle){ cout<<"please input the data:"; cin>>x; if(x!=0){ s=(node *)malloc(sizeof(node)); s->data=x; p->next=s; p=s; } else cycle=0; } p->next=NULL; p=head; head=head->next; free(p); return head; } int length(node *head){//单链表测长 int n=0; node *p=head; while(p!=NULL){ p=p->next; n++; } return n; } node *del(node *head, int num){//单链表删除 node *p1,*p2; p1=head; while(p1->data!=num&&p1->next!=NULL){ p2=p1; p1=p1->next; } if(num==p1->data){ if(p1==head){ head=p1->next; free(p1); } else{ p2->next=p1->next; free(p1); } } else cout<<"can not find "<<num; return head; } node *insert(node *head, int num){//插入链表--插入到第一个不小于num之后 node *p0,*p1,*p2; p1=head; p2=(node*)malloc(sizeof(node)); p2->data=num; while(p2->data>p1->data&&p1->next!=NULL){ p0=p1; p1=p1->next; } if(p2->data<=p1->data){ if(p1==head){ p2->next=head; head=p2; } else{ p2->next=p1; p0->next=p2; } } else{ p2->next=NULL; p1->next=p2; } return head; } node *reverse(node *head){//单链表的逆置 node *pre,*now; pre=NULL; now=head; while(now!=NULL){ node *temp=now->next; now->next=pre; pre=now; now=temp; } head=pre; return head; } int main(){ node *head; int n,del_num,insert_num; head=creat(); cout<<"头结点数值:"<<head->data; cout<<"\n delete_num:"; cin>>del_num; head=del(head,del_num); cout<<"头结点数值:"<<head->data; cout<<"\n insert_num:"; cin>>insert_num; head=insert(head,insert_num); cout<<"头结点数值:"<<head->data; return 0; }
相关文章推荐
- [李景山php]每天laravel-20160920|Writer-2
- 嵌入式开发第10天(高级议题,C语言结束)
- win64 Python下安装PIL出错解决
- Java内容回顾
- JAVA SE 面向对象笔记
- 深入理解Java反射
- struts2类型转换器
- phpcms v9模板制作常用代码集合
- Java BIO NIO AIO(转)
- C语言setreuid()函数:设置真实及有效的用户识别码
- java STL
- php使用simple_html_dom解析HTML示例
- 机器学习中的相似性度量 (多种几何距离定义)
- C# .net 使用 SmtpClient 发邮件 ,发送邮箱的配置
- C++元编程思想(译)
- 基于c++或C的开源搜索引擎
- 知道这20个正则表达式,能让你少写1,000行代码
- getppid()
- C语言字符串指针与字符数组的区别
- VC++6.0常用快捷键及对快捷键使用的看法(转)