159 向有序的环形单链表中插入新节点
Table of Contents

ac

一个环形单链表从头节点 head 开始不降序,同时由最后的节点指回头节点。给定这样一个环形单链表的头节点 head  一个整数 num 请生成节点值为 num 的新节点,并插入到这个环形链表中,保证调整后的链表依然有序。

include

using namespace std;

struct list_node{
int val;
struct list_node * next;
};

list_node * input_list(void)
{
int n, val;
list_node * phead = new list_node();
list_node * cur_pnode = phead;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == 1) {
cur_pnode->val = val;
cur_pnode->next = NULL;
}
else {
list_node * new_pnode = new list_node();
new_pnode->val = val;
new_pnode->next = NULL;
cur_pnode->next = new_pnode;
cur_pnode = new_pnode;
if (i == n) {
new_pnode->next = phead;
}
}
}
return phead;
}

list_node * insert_num(list_node * head, int num)
{
//////在下面完成代码
list_node pPre = head;
list_node
p = head->next;
while(p != head && p->val < num){
list_node* pNext = p->next;
pPre = p;
p = pNext;
}
list_node * new_pnode = new list_node();
new_pnode->val = num;

new_pnode->next = p;
pPre->next = new_pnode;

return head;

}

void print_list(list_node * head)
{
list_node * h = head;
while (1) {
printf("%d ", head->val);
if (head->next == h) break;
head = head->next;
}
puts("");
}

int main ()
{
list_node * head = input_list();
int n;
scanf("%d", &n);
list_node * new_head = insert_num(head, n);
print_list(new_head);
return 0;
}
```