在有序链表中插入结点
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; }
必需注意,当要插入的结点在链表的第一位,和最后一位的特殊情况。
相关文章推荐
- 链表(三)——链表删除冗余结点&插入结点到有序链表
- 第十八周项目一(6):将值为x的结点插入到建立起来的有序链表中
- 从键盘读入n个整数(升序),请编写算法实现: 建立带表头结点的单链表; 显示单链表,(形如:H->10->20->30->40); 在有序单链表中插入新的数据元素x; 将单链表就地逆
- 数据结构与算法分析笔记与总结(java实现)--链表9:有序环形链表中插入新结点问题
- 有序链表插入新结点的改进
- 有序的循环链表中插入结点
- 【数据结构作业二】写出单链表结点的结构体类型定义及查找、插入、删除算法,并以单链表作存储结构,实现有序表的合并
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- 在一个递增有序链表中插入新结点并保持链表递增顺序不变
- 链表(三)——链表删除冗余结点&插入结点到有序链表
- 向头指针为 L的有序单链表(从小到大有序)中插入一个结点,使插入后链表仍然有序
- 单链表之插入删除结点
- 单链表之插入删除结点
- C语言实现链表之单向链表(七)尾结点后插入结点
- 单链表中头结点的有无. 并讨论下有无头结点在单链表的创建,打印,插入,逆置,删除中的区别.
- 师--链表的结点插入
- 面试系列之三:C艹在双链表中插入结点
- 师--链表的结点插入
- K个有序链表共N个结点在O(NlgK)时间合并为一个新的有序链表头文件C语言
- 链表操作 对链表进行输入,插入,删除结点,按关键字进行查找操作 C语言