对于单链表的介绍部分参考自博文数组、单链表和双链表介绍 以及 双向链表的C/C++/Java实现

  1. 单链表介绍

  单向链表(单链表)是链表的一种,它由节点组成,每个节点都包含下一个节点的指针。

   1.1 单链表的示意图

  

  表头为空,表头的后继节点是"节点10"(数据为10的节点),"节点10"的后继节点是"节点20"(数据为10的节点),...

   1.2 单链表添加节点

  

  在"节点10"与"节点20"之间添加"节点15"
  添加之前:"节点10" 的后继节点为"节点20"。
  添加之后:"节点10" 的后继节点为"节点15",而"节点15" 的后继节点为"节点20"。

  需要注意的是在链表头部和其他地方添加结点是不一样的。

  在链表头部添加结点的关键代码为:

  1. NodePointer ptr = new Node();
  2. ptr->data = val;
  3. ptr->next = head;
  4. head = ptr;

  在其他地方添加结点的关键代码为:

  1. NodePointer ptr = new Node(), tmpPtr = head;
  2. ptr->data = val;
  3. while(...){...}
  4. ptr->next = tmpPtr->next;
  5. tmpPtr->next = ptr;

   1.3 单链表删除节点

  

  删除"节点30"
  删除之前:"节点20" 的后继节点为"节点30",而"节点30" 的后继节点为"节点40"。
  删除之后:"节点20" 的后继节点为"节点40"。

  需要注意的是在链表首部、尾部和其他地方删除结点是不一样的。

  在链表首部删除结点的关键代码为:

  1. NodePointer ptr = head, tmpPtr;
  2. ...if (pos == ) // 在链表第一个位置
  3. {
  4. head = ptr->next;
  5. delete ptr;
  6. }

  在链表尾部删除结点的关键代码为:

  1. NodePointer ptr = head, tmpPtr;
  2. while (...){...}
  3. tmpPtr = ptr->next;
  4. ptr->next = NULL;
  5. delete tmpPtr;

  在其他地方删除结点的关键代码为:

  1. NodePointer ptr = head, tmpPtr;
  2. while(...){...}
  3. tmpPtr = ptr->next;
  4. ptr->next = tmpPtr->next;
  5. delete tmpPtr;

  2. 代码实现

  对于单链表,我定义了一个这样的类LinkedList

  1. // linkedlist.h
  2. #ifndef LINKEDLIST
  3. #define LINKEDLIST
  4.  
  5. #include <iostream>
  6. #include <cassert>
  7.  
  8. using namespace std;
  9.  
  10. typedef int ElementType;
  11.  
  12. class Node
  13. {
  14. public:
  15. ElementType data;
  16. Node * next;
  17. };
  18. typedef Node * NodePointer;
  19.  
  20. class LinkedList
  21. {
  22. public:
  23. LinkedList();
  24. virtual ~LinkedList();
  25. LinkedList(const LinkedList& origlist);         // 拷贝构造函数
  26. LinkedList& operator=(const LinkedList& origlist);  // 赋值运算符重载
  27. void initList(ElementType * arr, int len);
  28. bool isEmpty();
  29. bool addNode(const int pos, const ElementType val);
  30. bool deleteNode(const int pos);
  31. void displayNodes();
  32. NodePointer getNode(const int pos);
  33. int getLenOfList();
  34.  
  35. private:
  36. NodePointer head;
  37.  
  38. };
  39.  
  40. #endif // LINKEDLIST

  实现代码如下:

  1. // linkedlist.cpp
  2. #include "linkedlist.h"
  3.  
  4. LinkedList::LinkedList()
  5. {
  6. head = NULL;
  7. }
  8.  
  9. LinkedList::~LinkedList()
  10. {
  11. NodePointer ptr = head, tmpPtr;
  12. while (ptr != NULL)
  13. {
  14. tmpPtr = ptr;
  15. ptr = ptr->next;
  16. delete tmpPtr;
  17. }
  18. }
  19.  
  20. LinkedList::LinkedList(const LinkedList& origlist)
  21. {
  22. //head = origlist.head; // 很容易写成这样,这样会造成浅拷贝
  23. NodePointer ptr = origlist.head;
  24. int i = ;
  25. while (ptr != NULL)
  26. {
  27. addNode(i, ptr->data);
  28. ptr = ptr->next;
  29. i++;
  30. }
  31. }
  32.  
  33. LinkedList& LinkedList::operator=(const LinkedList& origlist)
  34. {
  35. //head = origlist.head; // 很容易写成这样,这样会造成浅拷贝
  36. NodePointer ptr = origlist.head;
  37. int i = ;
  38. while (ptr != NULL)
  39. {
  40. addNode(i, ptr->data);
  41. ptr = ptr->next;
  42. i++;
  43. }
  44. return *this;
  45. }
  46.  
  47. void LinkedList::initList(ElementType * arr, int len)
  48. {
  49. for (int i = ; i < len; i++)
  50. {
  51. addNode(i, arr[i]);
  52. }
  53. }
  54.  
  55. bool LinkedList::isEmpty()
  56. {
  57. return head == NULL;
  58. }
  59.  
  60. bool LinkedList::addNode(const int pos, const ElementType val)
  61. {
  62. bool success = true;
  63. int len = getLenOfList();
  64. // assert(0 <= pos <= len);
  65. if (pos < || pos > len)
  66. {
  67. cerr << "The node at position " << pos << " you want to add is less than zero or larger than "
  68. << "the length of list ." << endl;
  69. success = false;
  70. throw out_of_range("out_of_range");
  71. }
  72. else
  73. {
  74. NodePointer ptr = new Node();
  75. ptr->data = val;
  76. if (pos == ) // 如果添加的元素在第1个
  77. {
  78. ptr->next = head;
  79. head = ptr;
  80. }
  81. else // 其他
  82. {
  83. NodePointer tmpPtr = head;
  84. int count = ;
  85. while (tmpPtr != NULL && count < pos - )
  86. {
  87. tmpPtr = tmpPtr->next;
  88. count++;
  89. }
  90. ptr->next = tmpPtr->next;
  91. tmpPtr->next = ptr;
  92. }
  93.  
  94. }
  95.  
  96. return success;
  97. }
  98.  
  99. bool LinkedList::deleteNode(const int pos)
  100. {
  101. bool success = true;
  102. int len = getLenOfList();
  103. if (len == )
  104. {
  105. cerr << "There is no element in the list." << endl;
  106. success = false;
  107. }
  108. else
  109. {
  110. NodePointer ptr = head, tmpPtr;
  111. int count = ;
  112. // assert(0 <= pos <= len);
  113. if (pos < || pos > len - )
  114. {
  115. cerr << "The node at position " << pos << " you want to delete is less than zero or larger than "
  116. << "the length of list ." << endl;
  117. success = false;
  118. throw out_of_range("out_of_range");
  119. }
  120. else if (pos == ) // 在链表第一个位置
  121. {
  122. head = ptr->next;
  123. delete ptr;
  124. }
  125. else if (pos == len - ) // 在链表最后一个位置
  126. {
  127. while (ptr != NULL && count < pos - )
  128. {
  129. ptr = ptr->next;
  130. count++;
  131. }
  132. tmpPtr = ptr->next;
  133. ptr->next = NULL;
  134. delete tmpPtr;
  135. }
  136. else // 其他
  137. {
  138. while (ptr != NULL && count < pos - )
  139. {
  140. ptr = ptr->next;
  141. count++;
  142. }
  143. tmpPtr = ptr->next;
  144. ptr->next = tmpPtr->next;
  145. delete tmpPtr;
  146. }
  147. }
  148. return success;
  149. }
  150.  
  151. void LinkedList::displayNodes()
  152. {
  153. int len = getLenOfList();
  154. if (len == )
  155. {
  156. cerr << "There is no element in the list." << endl;
  157. }
  158. else
  159. {
  160. NodePointer ptr = head;
  161. int sequence = ;
  162. while (ptr != NULL)
  163. {
  164. cout << "Seq: " << sequence << "; Data: " << ptr->data << "."<< endl;;
  165. ptr = ptr->next;
  166. sequence++;
  167. }
  168. }
  169.  
  170. }
  171.  
  172. NodePointer LinkedList::getNode(const int pos)
  173. {
  174. int len = getLenOfList();
  175. if (len == )
  176. {
  177. cerr << "There is no element in the list." << endl;
  178. return NULL;
  179. }
  180. else
  181. {
  182. // assert(0 <= pos <= len);
  183. if (pos < || pos > len - )
  184. {
  185. cerr << "The item at position " << pos << " you want to get is less than zero or "
  186. << "larger than the length of list." << endl;
  187. throw out_of_range("out_of_range");
  188. // return NULL;
  189. }
  190. else
  191. {
  192. NodePointer ptr = head;
  193. int count = ;
  194. while (ptr != NULL && count < pos)
  195. {
  196. ptr = ptr->next;
  197. count++;
  198. }
  199. return ptr;
  200. }
  201. }
  202. }
  203.  
  204. int LinkedList::getLenOfList()
  205. {
  206. int len = ;
  207. NodePointer ptr = head;
  208. while (ptr != NULL)
  209. {
  210. len++;
  211. ptr = ptr->next;
  212. }
  213. return len;
  214. }

linkedlist.cpp

  Boost单元测试代码如下:

  1. // BoostUnitTest.cpp
  2. #define BOOST_TEST_MODULE LinkedList_Test_Module
  3.  
  4. #include "stdafx.h"
  5. #include "D:\VSProject\Algorithm\List\LinkedList\SingleLinkedList_BasedOnPointer\SingleLinkedList\SingleLinkedList\linkedlist.h"
  6.  
  7. struct LinkedList_Fixture
  8. {
  9. public:
  10. LinkedList_Fixture()
  11. {
  12. testLinkedList = new LinkedList();
  13. }
  14. ~LinkedList_Fixture()
  15. {
  16. delete testLinkedList;
  17. }
  18.  
  19. LinkedList * testLinkedList;
  20.  
  21. };
  22.  
  23. BOOST_FIXTURE_TEST_SUITE(LinkedList_Test_Suite, LinkedList_Fixture)
  24.  
  25. BOOST_AUTO_TEST_CASE( LinkedList_Normal_Test )
  26. {
  27. // isEmpty --------------------------------------------
  28. BOOST_REQUIRE(testLinkedList->isEmpty() == true);
  29.  
  30. // getLenOfList ---------------------------------------
  31. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  32.  
  33. // addNode & getNode ---------------------------------
  34. BOOST_REQUIRE(testLinkedList->addNode(, ) == true);
  35. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  36. BOOST_REQUIRE((testLinkedList->getNode())->next == NULL);
  37. BOOST_REQUIRE(testLinkedList->isEmpty() == false);
  38. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  39.  
  40. BOOST_REQUIRE(testLinkedList->addNode(, ) == true);
  41. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  42. BOOST_REQUIRE((testLinkedList->getNode())->next == NULL);
  43. BOOST_REQUIRE(testLinkedList->isEmpty() == false);
  44. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  45.  
  46. BOOST_REQUIRE(testLinkedList->addNode(, ) == true);
  47. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  48. BOOST_REQUIRE((testLinkedList->getNode())->next != NULL);
  49. BOOST_REQUIRE(testLinkedList->isEmpty() == false);
  50. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  51.  
  52. // deleteNode -----------------------------------------
  53. BOOST_REQUIRE(testLinkedList->deleteNode() == true);
  54. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  55. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  56.  
  57. BOOST_REQUIRE(testLinkedList->deleteNode() == true);
  58. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  59. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  60.  
  61. BOOST_REQUIRE(testLinkedList->deleteNode() == true);
  62. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  63.  
  64. // initList -------------------------------------------
  65. int arr[] = { , , };
  66. int len = sizeof(arr) / sizeof(int);
  67. testLinkedList->initList(arr, len);
  68. BOOST_REQUIRE(testLinkedList->getLenOfList() == );
  69. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  70. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  71. BOOST_REQUIRE((testLinkedList->getNode())->data == );
  72. BOOST_REQUIRE((testLinkedList->getNode())->next == NULL);
  73.  
  74. }
  75.  
  76. BOOST_AUTO_TEST_CASE(LinkedList_Abnormal_Test)
  77. {
  78. int arr[] = { , , };
  79. int len = sizeof(arr) / sizeof(int);
  80. testLinkedList->initList(arr, len);
  81.  
  82. // addNode -------------------------------------------
  83. BOOST_REQUIRE_THROW(testLinkedList->addNode(-, ), out_of_range);
  84. BOOST_REQUIRE_THROW(testLinkedList->addNode(, ), out_of_range);
  85.  
  86. // deleteNode ----------------------------------------
  87. BOOST_REQUIRE_THROW(testLinkedList->deleteNode(-), out_of_range);
  88. BOOST_REQUIRE_THROW(testLinkedList->deleteNode(), out_of_range);
  89.  
  90. // getNode --------------------------------------------
  91. BOOST_REQUIRE_THROW(testLinkedList->getNode(-), out_of_range);
  92. BOOST_REQUIRE_THROW(testLinkedList->getNode(), out_of_range);
  93.  
  94. }
  95.  
  96. BOOST_AUTO_TEST_CASE(LinkedList_CopyConstuctor_Test)
  97. {
  98. int arr[] = { , , };
  99. int len = sizeof(arr) / sizeof(int);
  100. testLinkedList->initList(arr, len);
  101.  
  102. //LinkedList * testLinkedList2(testLinkedList); // 特别容易写成这样,这样导致的结果就是testLinkedList2和
  103. // testLinkedList指向同一块内存这样的写法才是正确的
  104. // 该句等同于
  105. // LinkedList * testLinkedList2;
  106. // testLinkedList2 = testLinkedList;
  107. //LinkedList testLinkedList2(*testLinkedList); // 要不就这样子定义,只不过此时testLinkedList2不是一个指针
  108. LinkedList * testLinkedList3 = new LinkedList(*testLinkedList);
  109. BOOST_REQUIRE(testLinkedList3->getLenOfList() == );
  110. BOOST_REQUIRE((testLinkedList3->getNode())->data == );
  111. BOOST_REQUIRE((testLinkedList3->getNode())->data == );
  112. BOOST_REQUIRE((testLinkedList3->getNode())->data == );
  113. BOOST_REQUIRE((testLinkedList3->getNode())->next == NULL);
  114. }
  115.  
  116. BOOST_AUTO_TEST_CASE(LinkedList_EqualOperator_Test)
  117. {
  118. int arr[] = { , , };
  119. int len = sizeof(arr) / sizeof(int);
  120. testLinkedList->initList(arr, len);
  121.  
  122. // LinkedList * testLinkedList2 = testLinkedList; // 错误的写法
  123. LinkedList * testLinkedList2 = new LinkedList();
  124. *testLinkedList2 = *testLinkedList;
  125.  
  126. BOOST_REQUIRE(testLinkedList2->getLenOfList() == );
  127. BOOST_REQUIRE((testLinkedList2->getNode())->data == );
  128. BOOST_REQUIRE((testLinkedList2->getNode())->data == );
  129. BOOST_REQUIRE((testLinkedList2->getNode())->data == );
  130. BOOST_REQUIRE((testLinkedList2->getNode())->next == NULL);
  131. }
  132.  
  133. BOOST_AUTO_TEST_SUITE_END()

BoostUnitTest.cpp

  本篇博文的代码均托管到Taocode : http://code.taobao.org/p/datastructureandalgorithm/src/.

"《算法导论》之‘线性表’":基于指针实现的单链表的更多相关文章

  1. "《算法导论》之‘线性表’":基于数组实现的单链表

    对于单链表,我们大多时候会用指针来实现(可参考基于指针实现的单链表).现在我们就来看看怎么用数组来实现单链表. 1. 定义单链表中结点的数据结构 typedef int ElementType; cl ...

  2. JavaScript 数据结构与算法之美 - 线性表(数组、栈、队列、链表)

    前言 基础知识就像是一座大楼的地基,它决定了我们的技术高度. 我们应该多掌握一些可移值的技术或者再过十几年应该都不会过时的技术,数据结构与算法就是其中之一. 栈.队列.链表.堆 是数据结构与算法中的基 ...

  3. ACM金牌选手算法讲解《线性表》

    哈喽,大家好,我是编程熊,双非逆袭选手,字节跳动.旷视科技前员工,ACM亚洲区域赛金牌,保研985研究生,分享算法与数据结构.计算机学习经验,帮助大家进大厂~ 公众号:『编程熊』 文章首发于: ACM ...

  4. 已知长度为n的线性表采用顺序结构,写一算法删除该线性表中所有值为item的元素

    /** * @author:(LiberHome) * @date:Created in 2019/2/27 23:34 * @description: * @version:$ */ /*已知长度为 ...

  5. 数据结构与算法系列2 线性表 使用java实现动态数组+ArrayList源码详解

    数据结构与算法系列2 线性表 使用java实现动态数组+ArrayList源码详解 对数组有不了解的可以先看看我的另一篇文章,那篇文章对数组有很多详细的解析,而本篇文章则着重讲动态数组,另一篇文章链接 ...

  6. 数据结构(1) 第一天 算法时间复杂度、线性表介绍、动态数组搭建(仿Vector)、单向链表搭建、企业链表思路

    01 数据结构基本概念_大O表示法 无论n是多少都执行三个具体步骤 执行了12步 O(12)=>O(1) O(n) log 2 N = log c N / log c N (相当于两个对数进行了 ...

  7. 数据结构与算法系列2 线性表 链表的分类+使用java实现链表+链表源码详解

    数据结构与算法系列2.2 线性表 什么是链表? 链表是一种物理存储单元上非连续,非顺序的存储结构,数据元素的逻辑顺序是通过链表的链接次序实现的一系列节点组成,节点可以在运行时动态生成,每个节点包括两个 ...

  8. javascript实现数据结构与算法系列:线性表的静态单链表存储结构

    有时可借用一维数组来描述线性链表,这就是线性表的静态单链表存储结构. 在静态链表中,数组的一个分量表示一个结点,同时用游标(cur)代替指针指示结点在数组中的相对位置.数组的第0分量可看成头结点,其指 ...

  9. 数据结构导论 四 线性表的顺序存储VS链式存储

    前几章已经介绍到了顺序存储.链式存储 顺序存储:初始化.插入.删除.定位 链式存储:初始化.插入.删除.定位 顺序存储:初始化 strudt student{ int ID://ID char nam ...

随机推荐

  1. Java异常处理-----运行时异常(RuntimeException)

    RuntimeException RunntimeException的子类: ClassCastException 多态中,可以使用Instanceof 判断,进行规避 ArithmeticExcep ...

  2. 1.cocos2dx 3.2环境搭建

    1        所需软件 jdk-7u25-windows-i586.exe python-2.7.8.amd64.msi cocos2d-x-3.2.zip apache-ant-1.9.4.zi ...

  3. JAVA面向对象-----值交换(基本数据类型 数组类型 对象的值 字符串的)

    JAVA面向对象-–值交换 基本数据类型交换 数组类型交换 对象的值交换 字符串的值交换 恩,没错,又是贴图,请大家见谅,我也是为了多写几个文章,请大家谅解. 字符串的值交换: 交换值失败. 这个文章 ...

  4. Linux proc/pid/task/tid/stat文件详解

    [root@localhost ~]# cat /proc/6873/stat6873 (a.out) R 6723 6873 6723 34819 6873 8388608 77 0 0 0 419 ...

  5. 04_关于元数据,ResultSetMetaData对象以及API方法介绍

     ResultSetMetaData对象 元数据,可以理解为数据的数据 Jdbc中的元数据是指数据库.表.列的定义信息. ResultSetMetaData对象表示结果集ResultSet对象的元 ...

  6. Python图片处理库之PIL

    这个模块对于Python2.7 的windows64位电脑而言,还真的是不好找啊.这里分享一个下载链接吧,需要的朋友可以下载下来.PIL For Windows64 Python2.7下面分享一下这个 ...

  7. Runtime系列(二)--Runtime的使用场景

    Runtime 理解介绍的文章非常多,我只想讲讲Runtime 可以用在哪里,而我在项目里哪些地方用到了runtime.多以实际使用过程为主,来介绍runtime的使用. * 那么runtime 怎么 ...

  8. 安卓java.lang.IllegalStateException: The specified child already has a parent.解决方案

    在使用ViewPager的时候遇到一个错误java.lang.IllegalStateException: The specified child already has a parent. You ...

  9. 【Unity技巧】LOGO闪光效果

    写在前面 本文参考了风宇冲的博文,在按照这篇博文实现LOGO闪光时,发现了一些问题.最严重的就是背景无法透明,看上去背景始终是黑色的:其次就是各个变量的意义不是非常明确,调节起来不方便:而且在闪光条的 ...

  10. Java进阶(三十一) Web服务调用

    Java进阶(三十一) Web服务调用 前言 有朋友问了一个问题:如何调用已知的音乐服务接口,服务文档如下: https://www.evernote.com/shard/s744/sh/c37cd5 ...