解题思路:与有序单链表类似,只不过加了尾指针指向链表头部
#include<iostream>
using namespace std;
typedef struct TNode
{
int data;
struct TNode* next;
}TNode;
TNode* insertNum(TNode* head, int num)
{
TNode* node = new TNode;
node->data = num;
node->next = NULL;
if (!head)
{
node->next = node;
return node;
}
if (head->data > num)
{
node->next = head;
head->next = node;
return node;
}
TNode* pre = head;
TNode* cur = head->next;
while (cur != head&&cur->data < num)
{
pre = cur;
cur = cur->next;
}
node->next = cur;
pre->next = node;
return head;
}
int main()
{
int num;
TNode* head = NULL;
int A[] = { 0, 11, 3, 4, 3, 2, 10, 44 };
int len = sizeof(A) / sizeof(A[0]);
for (int i = 0; i < len; i++)
{
head = insertNum(head, A[i]);
}
int i = 0;
for (TNode* cur = head; i < len; cur = cur->next,i++)
cout << cur->data<<endl;
return 0;
}
循环单链表的遍历: