#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; }输出:
原文地址:http://blog.csdn.net/shltsh/article/details/46497737