您的位置:首页 > 其它

在有序链表中插入结点

2012-12-08 02:44 225 查看
#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;
}


必需注意,当要插入的结点在链表的第一位,和最后一位的特殊情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐