已知有序(非递减)带头结点的链表。现需要插入一个值为n的结点,保证该链表依然有序。如图示,第一、二行是键盘输入,第三、四行是输出。第一行是建立链表,0表示结束链表建立(0不存入链表)。第二行3表示插入值为3的结点,保证链表依然有序。当输入的链表无序时,输出链表无序(不做插入操作)。请在/******start******/和/******end******/注释行中间完成相关代码。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <malloc.h>
typedef struct _node
{
int data;
struct _node* next;
} node;
node* create(); //建立带头结点的链表
void out(node* head); //输出链表
int insert(node* head, int value); //将值为value的结点插入到链表中,依然保证升序
int main(void)
{
int value, result;
node* head;
printf("Input: ");
head = create();
scanf("%d", &value);
printf("Output: ");
out(head); //输出原链表
result = insert(head, value);
if (result == 0)
{
printf("The link is disorder!\n");
}
else
{
out(head);
}
return 0;
}
node* create()
{
int n, i;
node* head, * p, * q;
head = (node*)malloc(sizeof(node));
head->next = NULL;
q = head;
i = 0;
scanf("%d", &n);
while (n != 0)
{
p = (node*)malloc(sizeof(node));//i为奇数插在开头,偶数插在结尾
p->data = n;
if (i % 2)
{
p->next = head->next;
head->next = p;
}
else
{
p->next = q->next;
q->next = p;
q = q->next;
}
i++;
scanf("%d", &n);
}
return head;
}
void out(node* head)
{
node* p = head->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/******start******/
int insert(node* head, int value) {
node* p, * q;//q,p相邻
node* s = (node*)malloc(sizeof(node));
int i, j;
p = head->next;
q = head;
while (p != NULL) {
if (p->next != NULL && p->data > p->next->data) {
return 0;//注意if里面顺序
}
if (p->data > value) {
s->next = p;
s->data = value;
q->next = s;
q = p;
p = p->next;
break;
}
else if (p->data < value) {
q = p;
p = p->next;
}
}
if (p == NULL && q->data < value) {
q->next = s;
s->data = value;
}
return 1;
}
/******end******/