数据结构链表——双链表
2015-07-24 22:58
423 查看
相对于单链表而言,双链表多了一个指向前方的指针,要注意的是头节点的前向指针始终为空。
与单链表一致的是,判断双链表是否为空,都是通过判断头节点的下一个节点是否为空来判断的。
双链表的操作与单链表的操作略有不同,主要是在插入操作和删除操作部分,有些额外的指针需要处理,另外特殊情况也需要考虑到,比如插入/删除之前链表为空。
代码如下:
与单链表一致的是,判断双链表是否为空,都是通过判断头节点的下一个节点是否为空来判断的。
双链表的操作与单链表的操作略有不同,主要是在插入操作和删除操作部分,有些额外的指针需要处理,另外特殊情况也需要考虑到,比如插入/删除之前链表为空。
代码如下:
#include<stdlib.h> #include<iostream> struct List{ int val; List* pre; List* next; }; List* initList( List **L )//make an empty List { *L = ( List* )malloc( sizeof( struct List ) ); (*L)->next = NULL; //this is very important (*L)->pre = NULL; return *L; } bool isEmpty( List* L) //test the list is an empty list or not { return L->next == NULL; } void insert( List* L, int x ) { List* tmp = ( List* )malloc( sizeof( struct List ) ); if( tmp == NULL ) std::cerr << "MEMORY OUT!" << std::endl; tmp->val = x; if( L->next == NULL )//the list is empty before insert the element x { tmp->next = L->next; tmp->pre = L; L->next = tmp; } else // the list is not empty { tmp->next = L->next; tmp->next->pre = tmp; tmp->pre = L; L->next = tmp; } } List* findPos( List* L, int x )//find element x in List L, return the priori list node { List* position; List* tmp = L->next; if( L->next == NULL ) return position; while( tmp != NULL && tmp->val != x ) tmp = tmp->next; if( tmp->val == x) position = tmp; return position; } void deleteElem( List* L, int x )//delete element x in List { List* tmp; List* position = findPos( L, x ); if( position == NULL ) std::cerr << "No Elem!" << std::endl; else { if( position->next == NULL ) //find the elem in the last node { position->pre->next = NULL; free( position ); } else //find the element in the middle of List { position->next->pre = position->pre; position->pre->next = position->next; free( position ); } } } void deleteList( List *L )//delete the whole List { List *tmp; while( L->next != NULL ) { tmp = L->next; L->next->pre = L; L->next = L->next->next; free( tmp ); } } void outputList( List* L )//output the list { List* tmp = L; while( tmp->next != NULL ) { std::cout << tmp->next->val << " "; tmp = tmp->next; } std::cout << std::endl; } int main( int _argc, char **__argv) { int arrcnt = 10; int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List* L; initList( &L ); for( int i = 0; i < arrcnt; ++i ) insert( L, arr[i] ); outputList( L ); //List* pos = findPri( L, 5); //std::cout << pos->val << std::endl; deleteElem( L, 9 ); outputList( L ); deleteList( L ); std::cin.get(); return 0; }
相关文章推荐
- 数据结构之链表
- 数据结构实验之求二叉树后序遍历和层次遍历
- 1324: 算法2-2:有序线性表的有序合并
- 并发无锁队列学习(数据结构)
- hdoj 1896 Stones (优先队列)
- Java类和数据结构中常用的方法
- NYOJ 5 Binary String Matching(数据结构)
- 【算法与数据结构】直接插入排序算法
- 南阳oj 寻找球号(二) 数据结构 题目138
- 【字符串数据结构后缀系列Part3】后缀自动机的性质和应用
- 反转单链表的几种方法
- 数据结构之数组创建及操作
- 数据结构各种排序
- java数据结构和算法------图(最短路径Dijkstra)
- BZOJ 2038 小Z的袜子(hose) (莫队离线)
- 总结手游客户端笔试面试题(Cocos2dx客户端、C/C++、lua、数据结构算法等)
- 在什么需求下使用map这种数据结构
- 数据结构之 树的基本概念
- 数据结构之链表与数组(-)——数组和链表的简介
- 南阳oj 数据结构 题目739 笨蛋难题四