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
原创粉丝点击