往有序单循环链表的插入元素使原链表依旧有序
程序员文章站
2022-07-15 15:37:55
...
解题思路:与有序单链表类似,只不过加了尾指针指向链表头部
#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;
}
循环单链表的遍历: