数据结构链表之循环双链表
2015-07-27 22:14
405 查看
对于有头结点的双链表L,当L为空时,L->pre == L && L->next == L;
对循环双链表的插入操作,需要考虑到链表为空的特殊情况;
对循环上链表的删除操作,需要考虑到被删除元素为链表中最后一个元素的特殊情况。
具体代码如下:
对循环双链表的插入操作,需要考虑到链表为空的特殊情况;
对循环上链表的删除操作,需要考虑到被删除元素为链表中最后一个元素的特殊情况。
具体代码如下:
#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 = *L; //this is very important (*L)->pre = *L; return *L; } bool isEmpty( List* L) //test the list is an empty list or not { return ( L->next == L && L->pre == L ); } 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( isEmpty( L ) ) //the list is empty before insert the element x { tmp->next = L->next; tmp->pre = L; L->next = tmp; L->pre = 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 == L )//empty list return position; while( tmp != L && 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 == L ) std::cerr << "No Elem!" << std::endl; else { if( position->next == L ) //find the elem in the last node { position->pre->next = L; L->pre = position->pre; 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 != L ) { 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 != L ) { 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, 6 ); outputList( L ); deleteList( L ); std::cin.get(); return 0; }
相关文章推荐
- [数据结构] 字典树
- 数据结构---单链表(2)
- 数据结构表达式求值有关问题
- 数据结构链表之单循环链表
- 面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- 面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结 2015-07-27 20:49 13人阅读 评论(0) 收藏
- ZOJ 3886 Nico Number (线段树)
- 南阳oj 士兵杀敌(二) 题目116 NYOJ 数据结构
- 课程笔记 16:数据结构(清华) 图-邻接矩阵
- LeetCode 208. Implement Trie (Prefix Tree)
- 数据结构---单链表(1)
- 数据结构之并查集
- 【算法与数据结构】二叉树的构造
- 课程笔记 15:数据结构(清华) 图
- 数据结构之插入排序--折半插入排序
- 【自考】——数据结构导论(一)
- 数据结构实验:连通分量个数
- 数据结构实验之二叉树的建立与遍历
- 数据结构导论初步理解
- 数据结构上机实验之二分查找