您的位置:首页 > 其它

循环链表(3) - 遍历

2015-06-15 01:12 239 查看
在循环链表系列的前2篇文章中,已经介绍了循环链表的基本情况以及插入操作。本篇讨论如何对它进行遍历操作。



通常对普通链表进行遍历时,一般从头节点开始,并遇到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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: