当前位置:   article > 正文

有序链表的实现_链表node是哪个依赖

链表node是哪个依赖

有序链表的实现

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

struct Node {
	struct Node* next;
	int value;
};
  • 1
  • 2
  • 3
  • 4

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

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

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

void print_linklist(struct Node* head);

void delete_linklist(struct Node* head);

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

实现:

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号