线性表——链式存储结构之单链表
来源:互联网 发布:软件下载安装教程 编辑:程序博客网 时间:2024/06/04 17:54
#ifndef LINKLIST_H#define LINKLIST_H#include <stdint.h>#include <stdio.h>#include <stdlib.h>template <typename ElemType>class Node {public: Node() : data(ElemType()), next(NULL) {} Node(const ElemType &_data) : data(_data), next(NULL) {} Node(const ElemType &_data, Node<ElemType> *_next) : data(_data), next(_next) {} ~Node() {}public: ElemType data; Node<ElemType> *next;};template <typename ElemType>class SingleList {public: SingleList() : count(0) { if((head_node = new Node<ElemType>) == NULL) return; head_node->data = 0; head_node->next = NULL; } ~SingleList() { if (count != 0) { ClearList(); } if (head_node) { delete head_node; head_node = NULL; } }public: void InitList() { count = 0; head_node->data = 0; head_node->next = NULL; } bool ListEmpty() { return count == 0; } void ClearList() { Node<ElemType> *p, *q; p = head_node->next; while (p) { q = p->next; delete p; p = q; } head_node->next = NULL; count = 0; } void GetElem(uint32_t i, ElemType *e) { if ((i < 1) || (i > count)) { fprintf(stderr, "Out of list!\n"); return; } else { Node<ElemType> *p = head_node; for (int j = 0; j < i; ++j) { p = p->next; } *e = p->data; } } uint32_t LocateElem(ElemType e) { Node<ElemType> *p = head_node->next; for (int i = 1; i <= count; ++i) { if ((p != NULL) && (p->data == e)) { return i; } p = p->next; } fprintf(stderr, "Not in this list\n"); return -1; } void ListInsert(uint32_t i, ElemType *e) { if ((i < 1) || (i > count+1)) { fprintf(stderr, "Out of the list\n"); return; } else { Node<ElemType> *p = head_node; Node<ElemType> *q = new Node<ElemType>; q->data = *e; for (int j = 1; j < i; ++j) { p = p->next; } q->next = p->next; p->next = q; } ++count; } void ListDelete(uint32_t i, ElemType *e) { if ((i < 1) || (i > count+1)) { fprintf(stderr, "Out of the list\n"); return; } Node<ElemType> *p, *q; p = head_node; for (uint32_t j = 0; j < i; ++j) { q = p; p = p->next; } q->next = p->next; *e = p->data; --count; delete p; } uint32_t ListLength(void) { return count; }private: int count; Node<ElemType> *head_node;};#endif
后记:测试的时候,发现删除一个元素时,会导致整个链表被破坏了,在纸上画了半天,百思不得其解,最终将delete换成free,发现结果正确了,想到delete与free的区别,就意识到错哪了,竟然在Node的析构函数中,随手将next指针delete掉了。细节决定一切!
0 0
- 线性表——链式存储结构之单链表
- 线性表——链式存储结构之单链表
- 线性表——链式存储结构之循环单链表
- 【线性表】链式存储结构之:单链表
- 线性表-链式存储结构之单链表
- 线性表——链式存储结构之双链表
- 线性表——链式存储结构之循环双链表
- 线性表的链式存储结构——单链表
- 线性表——链式存储结构之循环单链表的应用
- JAVA数据结构之线性表的链式存储结构——单链表
- 线性表之链式存储结构
- 数据结构:线性表之链式存储结构
- 【线性表】链式存储结构之:双链表
- 线性表之链式存储结构
- 线性表-链式存储结构之双链表
- 线性表之链式存储结构
- 【数据结构】线性表之链式存储结构
- 【线性表】之链式存储结构
- texlive中文支持
- CodeIgniter “The filetype you are attempting to upload is not allowed.”解决
- makefile中的all和.PHONY的作用
- poj.1094
- ffmpeg(5):SDL相关学习
- 线性表——链式存储结构之单链表
- 组合算法 C++高效实现 (二进制辅助法)
- HTTP协议详解(真的很经典)
- SSH面试题整理
- 黑马程序员--C#中面向对象与面向过程
- hdu 1568 (log取对数 / Fib数通项公式)
- Altera笔记:Introduction to Parallel Computing with OpenCL
- 面试软件测试 智力题题目与部分答案
- Oracle 11.2.0.3.0 RAC Silent Install-3Nodes