c++ 实现双链表基本操作
2012-03-13 21:02
603 查看
#include <cstdlib> #include <iostream> #include <stdio.h> #include <conio.h> /*c++实现双链表的基本操作*/ using namespace std; typedef struct student { int data; struct student *pre; struct student *next; }dnode; //创立链表 dnode *creat() { dnode *head,*p,*s; int x,cycle=1; head=(dnode *)malloc(sizeof(dnode)); p=head; while(cycle) { cout<<"please input the data!"<<endl; cin>>x; if(x!=0) { s=(dnode *)malloc(sizeof(dnode)); s->data=x; p->next=s; s->pre=p; p=s; } else cycle=0; } head=head->next; head->pre=NULL; p->next=NULL; return head; } //打印链表 void print(dnode *head) { dnode *p,*s; p=head; cout<<"正序打印双链表:"<<endl; while(p->next!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<p->data<<endl; cout<<"逆序打印双链表:"<<endl; while(p->pre!=NULL) { cout<<p->data<<" "; p=p->pre; } cout<<p->data<<endl; } //双链表插入节点 dnode *insert(dnode *head,int num) { dnode *p0,*p1; p1=head; p0=(dnode *)malloc(sizeof(dnode)); p0->data=num; while(p0->data>p1->data&&p1->next!=NULL) { p1=p1->next; } if(p0->data<=p1->data) { if(head==p1) { p0->next=p1; p1->pre=p0; head=p0; } else { p1->pre->next=p0; p0->next=p1; p0->pre=p1->pre; p1->pre=p0; } } else { p1->next=p0; p0->pre=p1; p0->next=NULL; } return head; } //删除指定的节点 dnode *del(dnode *head,int num) { dnode *p1,*p2; p1=head; while(num!=p1->data&&p1->next!=NULL) p1=p1->next; if(num==p1->data) { if(p1==head) { head=head->next; head->pre=NULL; free(p1); } else if(p1->next==NULL) { p1->pre->next=NULL; free(p1); } else { p1->next->pre=p1->pre; p1->pre->next=p1->next; free(p1); } } else { cout<<"没有指定的节点"<<endl; } return head; } int main(int argc, char *argv[]) { int x; dnode *head=creat(); print(head); cout<<"输入要插入的数字:"<<endl; cin>>x; head=insert(head,x); print(head); cout<<"输入要删除的数字:"<<endl; cin>>x; head=del(head,x); print(head); system("PAUSE"); return EXIT_SUCCESS; }
相关文章推荐
- 双链表基本操作C++实现
- 循环双链表基本操作C++实现
- c++实现栈的基本操作
- 链式队列的基本操作实现c++
- 【数据结构】双向循环线性表的基本操作--C++/C实现
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果
- 循环双链表的基本操作实现
- C++实现二叉树的基本操作
- C++实现二叉树基本操作详解
- c++实现基本循环队列操作
- c++学习笔记—单链表基本操作的实现
- 顺序表基本操作的代码实现:C++实现
- 【数据结构】双向循环线性表的基本操作--C++/C实现
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果
- C++实现链表的基本操作及测试用例
- Deque C语言实现 && C++ STL基本操作
- C++实现栈的基本操作
- 详细的单链表基本操作C/C++实现
- c++ 队列基本操作实现
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果