双向链表的基本操作的实现

来源:互联网 发布:js json数组 编辑:程序博客网 时间:2024/05/18 00:46
<span style="font-family: Arial, Helvetica, sans-serif;">// double_link.cpp : 定义控制台应用程序的入口点。</span>
//#include "stdafx.h"#include"stdio.h"#include "stdlib.h"#include <string.h>typedef int ElemType;typedef struct DuLNode{ElemType   data;struct DuLNode *prior;struct DuLNode *next;}DuLNode,*DuLNodeList;//初始化链表;int InintList(DuLNodeList L){L = (DuLNodeList)malloc(sizeof(DuLNode));if (!L)   exit(-2);L->next = L;L->prior = L;return 1;}//建立链表;void DuLNodeListCreat(DuLNodeList L){DuLNodeList P=L;int x;printf("请输入链表的元素:(以0结束)\n");scanf_s("%d", &x, sizeof(x));while (x){DuLNodeList S = (DuLNodeList)malloc(sizeof(DuLNode));S->data = x;P->next = S;L->prior = S;S->prior = P;S->next = L;P = S;scanf_s("%d", &x, sizeof(x));}}//遍历链表;void DuLNodeListTraverse(DuLNodeList L){DuLNodeList P = L->next;if (P==L){printf("双向链表为空\n");return ;}while (P->next != L){printf("%d ", P->data);P = P->next;}printf("%d ", P->data);printf("\n");}//链表长度;int ListLength_DuL(DuLNodeList L){DuLNodeList p;int count;p = L->next;count = 0;while (p != L){count++;p = p->next;}return count;}//双链表的插入,在双链表中插入值为x的元素;DuLNodeList DuLNodeListinsert(DuLNodeList L,ElemType x){DuLNodeList p, r;p = L->next;r = (DuLNode*)malloc(sizeof(DuLNode));r->data = x;r->next = p->next;p->next->prior = r;r->prior = p;p->next = r;return L; }//删除链表中值为x的元素;int DuLNodeListDelete(DuLNodeList L, ElemType x){DuLNodeList P;P = L->next;while (P != L){if (P->data == x){P->next->prior = P->prior;P->prior->next = P->next;free(P);return 3;}else       P = P->next;}return 1;}int main(){int x, k;int ret;DuLNodeList L;L= (DuLNodeList)malloc(sizeof(DuLNode));do{printf("1.建立链表\n");printf("2.插入链表\n");printf("3.删除链表\n");printf("4.遍历链表\n");printf("0.结束链表\n");printf("please enter your choice(1-5)\n");scanf_s("%d", &k,sizeof(k));switch (k){case 1:InintList(L);DuLNodeListCreat(L);printf("创建成功!\n");break;case 2:printf("请输入要插入的元素:");scanf_s("%d ", &x,sizeof(x));DuLNodeListinsert(L,x);break;case 3:printf("请输入要删除元素的值:\n");scanf_s("%d", &x,sizeof(x));ret=DuLNodeListDelete(L,x);if (3==ret)printf("删除%d成功\n", x);else if (1 == ret)printf("链表中不存在元素%d\n", x);else printf("链表为空\n");break; case 4:printf("当前链表内容如下所列:\n");DuLNodeListTraverse(L);break;case 0:exit(0);}}while (k);}
此代码只供参考,如有纰漏请高手指正!
在双向链表的节点中有两个指针域,一个指向直接后继,一个指向直接前驱,编写代码时一定要注意指针指向问题,如果指针指向问题弄不明白,就会出现N多错误,甚至导致代码崩溃,以及死循环等等;以下代码的时间复杂度为O(n).

0 0