C++ 双链表的基本操作
来源:互联网 发布:安全数据防泄密厂家 编辑:程序博客网 时间:2024/05/22 03:52
在笔试面试过程中遇到的比较难一点点的编程,双链表就是其中之一了。对于缺少编程经验的同学而言更是如此,止步于这里大有人在。虽然我比较幸运没有遇到这样的问题,但是为了以防万一,或者说加深一下自己的印象,还是动手写了一把。以下就将我在VC6.0上调试通过的代码。
#include <stdio.h>#include <iostream.h>#include <stdlib.h>#include <string>using namespace std;typedef struct DoubleLinkList{int data;struct DoubleLinkList *prior,*next;}DLLNode;int n = 5;//双向链表的长度DLLNode *creatDLL(int n)//创建双向链表{cout<<"输入双向链表元素的个数:"<<n<<endl;DLLNode *head ;//= new DLLNode;DLLNode *ptr;head=(DLLNode *)malloc(sizeof(DLLNode));if (head == NULL){cout<<"can not find space!"<<endl;return 0;}head->next = NULL;head->prior = NULL;ptr = head;for (int i = 1;i<=n;i++)//输入一个则依次向后创建一个节点,最后一个节点的next为NULL{DLLNode *inset;inset = (DLLNode *)malloc(sizeof(DLLNode));if (inset==NULL){cout<<"can not find space!"<<endl;return 0;}cin>>inset->data;inset->next = ptr->next;inset->prior = ptr;ptr->next = inset;ptr = inset;}return head;}DLLNode *InsetDLL(DLLNode *head,int Num,int data)//在链表DLL中的第Num位置插入元素data{int i=0;if(Num>n||Num<0){cout<<"please input a right numble!"<<endl;return 0;}DLLNode *inset,*p;p = head;inset = (DLLNode *)malloc(sizeof(DLLNode));if (inset==NULL){cout<<"can not find space!"<<endl;return 0;}inset->data = data;while (i<Num-1){p = p->next;i++;}inset->next = p->next;inset->prior = p;p->next->prior = inset;p->next = inset;n++;return head;}DLLNode *DelNode(DLLNode *head,int Num)//删除双向链表的第Num个节点{int i = 0;if(Num>n||Num<0){cout<<"please input a right numble!"<<endl;return 0;}DLLNode *p;p = head;while (i < Num){p = p->next;i++;}p->next->prior = p->prior;p->prior->next = p->next;free(p);//节点p被删除,需要释放该内存n--;return head;}DLLNode *RevertDLL(DLLNode *head,int n)//双链表逆序{if (head->next == NULL){cout<<"this is a empty Link!"<<endl;return 0;}DLLNode *p,*q;p = head->next;q = head->next->next;p->next = head->prior;p->prior = q;while (q != NULL){p = q;q = q->next;p->next = p->prior;p->prior = q;}p->prior = head;head->next = p;free(q);return head;}void main(){DLLNode *p;p = creatDLL(n);//p = RevertDLL(p,5);p = InsetDLL(p,2,9);cout<<n<<endl;for (int i = 0;i<n;i++){cout<<p->next->data<<" ";p = p->next;}cout<<endl;}
这里链表创建的输入方式是输入一个就创建一个节点,可能会觉得不是很高效。当然也有一种方式就是一次输入所有的节点,然后将这些节点创建成双向链表。这里我就不贴代码上来了,大家自行发挥吧!
0 0
- C的大数基本操作
- C基本的读写操作
- 【C++】单链表的基本操作
- C++---文件的基本操作
- 【C#】特性的基本操作
- c++string的基本操作
- 双链表的基本操作
- 双链表的基本操作
- 双链表的基本操作
- 双链表的基本操作
- C的一些基本指针操作
- C的一些基本指针操作
- C语言链队列的基本操作
- 文件的基本操作 C语言版
- 二叉树的基本操作(C++)
- 链表的基本操作(C++)
- C++map的基本操作和使用
- c实现队列的基本操作
- 使用SQL语句清空数据库所有表的数据
- 19位编程大师集锦
- 谁动了你的需求?
- 主成成分分析pca算法 原理解析
- 业务流程图的绘制流程分享
- C++ 双链表的基本操作
- libevent 在 Android 上的一个改进
- 如何在 Ubuntu 12.04 Server 中安装图形用户界面
- 【黑马程序员】Java基础13:强大的正则
- 基于Linux的Samba开源共享解决方案测试(四)
- 业精于勤毁于嬉,行成于思毁于随
- Java基础之(九)-----Java中的IO流(一)【进阶必备】
- openLayers-Defining custom rules to style featuresl;
- 美媒惊人设想建议热火打劫 两换一交易阿西克