循环链表(3) - 遍历
2015-06-15 01:12
239 查看
在循环链表系列的前2篇文章中,已经介绍了循环链表的基本情况以及插入操作。本篇讨论如何对它进行遍历操作。
通常对普通链表进行遍历时,一般从头节点开始,并遇到null节点时停止。而在循环链表中,当第二次到达首节点时,遍历停止。
下面是循环链表遍历代码实现:
Circular Linked List is:
11 2 56 12
通常对普通链表进行遍历时,一般从头节点开始,并遇到null节点时停止。而在循环链表中,当第二次到达首节点时,遍历停止。
下面是循环链表遍历代码实现:
#include <iostream> //链表节点 struct Node { int data; Node *next; }; //在循环链表头部插入新的节点 void push(Node **head, int data) { Node *newNode = new Node; Node *temp = *head; newNode->data = data; newNode->next = *head; //如果链表不为空,则将最后一个节点的后向指针设置为新节点 //即新节点变成了新的头节点。 if (*head != NULL) { while (temp->next != *head) temp = temp->next; temp->next = newNode; } else newNode->next = newNode; //新节点做为链表第一个节点 *head = newNode; //调整头节点 } //打印循环链表 void printList(Node *head) { Node *temp = head; if (head != NULL) { do { std::cout << " " << temp->data << " "; temp = temp->next; } while (temp != head); } } int main() { //初始化链表为:[11]->2->56->12->[11],其中[11]表示同一个节点 Node *head = NULL; push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); std::cout<<"Circular Linked List: \n "; printList(head); return 0; }输出:
Circular Linked List is:
11 2 56 12
相关文章推荐
- WIN8 自定义控件添加到页面XAML报错的解决方法
- 回溯法
- 指出您的竞争对手在所有的SEO基础方面做得如何
- java list顺序
- 循环链表(2) - 插入节点至已排序链表
- ios 日记3 define和typedef(2)
- 同花顺公式
- Wampserver2.5配置虚拟主机出现403 Forbidden的处理方案
- 循环链表(1) - 介绍以及应用
- Android项目之——Activity悬浮并可拖动
- Android应用程序UI硬件加速渲染的Display List渲染过程分析
- Java中断正在运行的线程
- 黑马程序员-Java基础--类型转换、标识符、位运算符
- python 装饰器
- java 正则表达式的一些符号
- SEO计划中的特定任务
- CentOS在VirtualBox下安装增强软件,添加共享文件夹,Xshell/Xftp的安装与使用
- C++ Circle类
- 【转载】Direct3D HLSL介绍(上)
- 关于SQL的几道小题详解