前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >有序链表的实现

有序链表的实现

作者头像
From Zero
发布2021-02-22 11:16:53
2920
发布2021-02-22 11:16:53
举报
文章被收录于专栏:C语言C语言

有序链表的实现

链表的定义依赖于以下结构体:

代码语言:javascript
复制
struct Node {
	struct Node* next;
	int value;
};

链表依赖一个一个的节点连接而成,由每一个节点中的指向结构体类型的指针指向下一个节点。

现在给出n个数字,将它们按照从小到大的顺序依次插入链表中,所需相应函数的声明如下:

代码语言:javascript
复制
void insert(struct Node** head, int num);

void print_linklist(struct Node* head);

void delete_linklist(struct Node* head);

实现:

代码语言:javascript
复制
#include
#include

struct Node {
	struct Node* next;
	int value;
};

int main(void) {
	int n, num;
	scanf("%d", &n);

	struct Node* head = NULL;
	while (n--) {
		scanf("%d", &num);
		insert(&head, num);
	}
	print_linklist(head);
	delete_linklist(head);

}

void insert(struct Node** head, int num) {
	struct Node* t = *head, *temp = *head;
	struct Node* cur_node = (struct Node*)malloc(sizeof(struct Node));
	cur_node->next = NULL;
	cur_node->value = num;
	if (*head == NULL) {
		*head = cur_node;
	}
	else {
		if (t->value >= num) {
			cur_node->next = t;
			*head = cur_node;
			return;
		}
		while(t!=NULL) {
			if (t->value >= num) {
				cur_node->next = t;
				temp->next = cur_node;
				break;
			}
			temp = t;//指向上一个。
			t = t->next;
			if (t == NULL) {//放在最后面
				temp->next = cur_node;
			}
		}
	}
}

void print_linklist(struct Node* head) {
	struct Node* t = head;
	while (t != NULL) {
		printf("%d ", t->value);
		t = t->next;
	}
    printf("\n");
}

void delete_linklist(struct Node* head) {
	struct Node* t;
	while (head != NULL) {
		t = head->next;
		free(head);
		head = t;
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-02-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 有序链表的实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档