C++ 构造双向链表的实现代码
2016-04-26 10:50
676 查看
#include<iostream.h> using namespace std; template<class T> struct Node { Node<T> *pre; T data; Node<T>*next; }; template <class T> class DoubleLinkedList { public: DoubleLinkedList() { Node<T> *q = new Node<T>; if(q == NULL) { cout << "Fail to malloc the head node." << endl; return; } phead = q; phead->pre = NULL; phead->data = NULL; phead->next = NULL; // T i; cout << "Please input several integer number, input ctrl+z to the end: " << endl; while (cin >> i) { Node<T> *p = new Node<T>; if(p == NULL) { cout << "Fail to malloc a new node." << endl; return; } p->data = i; q->next = p; p->pre = q; p->next = NULL; } } int size() { Node<T> *p = phead->next; int count(0); while(p != NULL) { count++; p = p->next; } return count; } void print_elements() { Node<T> *p = phead->next; while(p != NULL) { cout << p->data << ""; p = p->next; } cout << endl; } void insert_element(int i, T e) { if(i <= this->size()) { Node<T> *m = phead; for(int j = 1; j < i; j++) { m = m->next; } Node<T> *n = m->next; Node<T> *p = new Node<T>; if(p == NULL) { cout << "Failed to malloc the node." << endl; } m->next = p; p->pre = m; p->data = e; p->next = n; n->pre = p; } else if(i == (this->size() + 1)) { Node<T>* m = phead; for(int j = 1; j < i; j++) { m = m->next; } Node<T> *p = new Node<T>; if(p == NULL) cout << "Failed to malloc the node." << endl; m->next = p; p->pre = m; p->data = e; p->next = NULL; } else cout << "Please input the position number equals or smaller than " << size()+1 << endl; // } void insert_element(T e) { Node<T> *m = phead; for(int j = 1; j <= size(); j++) { m = m->next; } Node<T> *p = new Node<T>; if(p == NULL) { cout << "Failed to malloc the node." << endl; } m->next = p; p->pre = m; p->data = e; p->next = NULL; } void delete_element(int i) { Node<T> *p = phead; for(int j = 0; j < i; j++) { p = p->next ; if(p == NULL) { cout << "The size of the list is " << size() << " ,Please input the right number." << endl; return; } } if(p->next != NULL) { Node<T> *m = p->pre; Node<T> *n = p->next; m->next = n; n->pre = m; delete p; } else { Node<T> *m = p->pre; m->next = NULL; delete p; } } private: Node<T>* phead; }
相关文章推荐
- C语言的setvbuf函数:设置文件流的缓冲区
- 值得学习的C语言开源项目
- C语言最优状态机规范
- C语言实现状态设计模式
- Keil uVision编译支持C++
- C++11新特性
- printf标准输出,右对齐
- C/C++字符串和数字互换方案收集(转)
- c++中vector的用法详解
- 如何优化C语言代码(程序员必读)
- 数组实现队列 C++实现(2)
- 关于c++常量定义
- c/c++ 数字转成字符串, 字符串转成数字
- C++中产生随机数
- C++中 public protected private 类成员的访问
- 关于优化C++的小知识
- 关于C++中的常量成员函数
- C++中string类对象的成员函数c_str()与C语言中字符串的联系
- C++读取配置文件
- C语言之程序编程规范