#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
struct node *inset_into_ordered_list(struct node *list, struct node *new_node);
int main(void)
{
struct node *p1 = malloc(sizeof(struct node));
struct node *p2 = malloc(sizeof(struct node));
struct node *p3 = malloc(sizeof(struct node));
struct node *ultimo = malloc(sizeof(struct node));
p1->value = 10;
p1->next = p2;
p2->value = 50;
p2->next = p3;
p3->value = 80;
p3->next = NULL;
ultimo->value = 142;
ultimo->next = NULL;
p1 = inset_into_ordered_list(p1, ultimo);
return 0;
}
struct node *inset_into_ordered_list(struct node *list, struct node *new_node)
{
struct node *cur = list, *prev = NULL;
while (cur->value <= new_node->value) {
prev = cur;
if (cur->next == NULL) { //nel caso nell'ultimo poszione della lista
new_node = cur->next;
return list;
}
else
cur = cur->next;
}
if (prev == NULL) { // nel caso nel primo poszione della lista
new_node->next = cur;
return new_node;
}
prev->next = new_node;
new_node->next = cur;
return list;
}
必需注意,当要插入的结点在链表的第一位,和最后一位的特殊情况。