https://leetcode.cn/problems/4ueAj6/
这道题整体上想插入数据有三种情况:
1、整个列表是空列表,需要返回插入的结点
2、整个列表只有一个结点,需要在头结点后插入新结点,随机把新结点的next指向头结点
3、整个列表的结点 >1 ,在插入新结点后要保证整个列表是循环升序的。
/**
* Definition for a Node.
* struct Node {
* int val;
* struct TreeNode *next;
* };
*/
struct Node* insert(struct Node* head, int insertVal) {
struct Node* cur = (struct Node*)malloc(sizeof(struct Node));
cur->val = insertVal;
cur->next = NULL;
//列表为空
if(head == NULL)
{
cur->next = cur;
return cur;
}
//列表只有一个结点
if(head->next == head)
{
cur->next = head;
head->next = cur;
return head;
}
//curr和next分别表示当前结点和下一个结点
struct Node* curr = head , *next = head->next;
//遍历整个循环链表
while(next != head )
{
if(curr->val <= cur->val && next->val >= cur->val)
{
break;
}
if(curr->val > next->val)
{
if(cur->val > curr->val || cur->val < next->val)
{
break;
}
}
curr = curr->next;
next = next->next;
}
curr->next = cur;
cur->next = next;
return head;
}