有序链表的实现

有序链表的实现

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

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

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

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

void insert(struct Node** head, int num);

void print_linklist(struct Node* head);

void delete_linklist(struct Node* head);

实现:

#include<malloc.h>
#include<stdio.h>

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;
	}
}

猜你喜欢

转载自blog.csdn.net/m0_51653236/article/details/113615646