数据结构(C语言)——双链表

有了单链表的编写经验,双链表变得格外容易。点击看前一篇-单链表

数据结构(C语言)——双链表_第1张图片

下面是代码:

#include
#include
#define E int
typedef struct node {
	E element;
	struct node* pre;
	struct node* next;
}node;
void initialise(node* head) {//初始化头节点
	head->element = 0;
	head->next = NULL;
	head->pre = NULL;
}
int add_node(node* head,int index,E ele) {
	node* tem = head->next;//先将下一节点指针给一个临时变量
	if (index < 1)return -1;
	while (--index && tem != NULL) {
		head= tem;
		tem = tem->next;//移动指向下一节点
	}
	if (index == 0 && tem == NULL) {
		node* ptr = (node*)malloc(sizeof(node));
		if (ptr == NULL)return -1;
		ptr->element = ele;
		ptr->pre = head;
		head->next = ptr;
		ptr->next = NULL;
		return 1;
	}
	else if (tem != NULL) {//在中间添加的情况
		node* ptr = (node*)malloc(sizeof(node));
		ptr->element = ele;
		ptr->pre = head;
		head->next = ptr;
		ptr->next = tem;
		tem->pre = ptr;
		return 1;
	}
	return -1;//没有这个位置的节点
}
print_node(node* head) {
	while (head->next != NULL) {
		head = head->next;//节点指针移动
		printf("%d\n", head->element);
	}
}
int del_node(node* head, E ele) {
	node* tem = head->next;
	int count = 0;
	while (tem != NULL) {
		if (tem->element == ele) {
			head->next = tem->next;
			if (tem->next != NULL)tem->next->pre = head;//如果是删的最后一个元素,这句话不用执行
			count++;
		}
		head = tem;
		tem = tem->next;//节点指针移动
	}
	if(!count)return -1;
	return 1;
}
node* find_node(node* head, E ele) {
	head = head->next;//先移动头节点指针
	while (head != NULL) {
		if (head->element == ele) {
			return head;
		}
		head = head->next;//移动到下一节点
	}
}
node* modif_node(node* head, int index,E ele) {
	head = head->next;//先移动头节点指针
	if (index < 1)return NULL;
	while (--index && head != NULL) {
		head = head->next;//继续移动到需要位置
	}
	if (head == NULL)return NULL;
	head->element = ele;
	return head;
}
int main() {
	node head;
	initialise(&head);
	
	for (int i = 1; i <= 8; i++) {
		add_node(&head, 1, 20*i);
	}
	add_node(&head, 9, 520);
	print_node(&head);
	printf("----------\n");
	del_node(&head, 160);
	print_node(&head);
	printf("----------\n");
	node* find = find_node(&head, 520);
	//找这个数据的前一个数据
	printf("%d\n", find->pre->element);
	printf("%d\n", find->element);
	printf("----------\n");
	node* mod = modif_node(&head,9 ,999);
	if(mod!=NULL)printf("%d\n", mod->element);
	printf("----------\n");
	print_node(&head);
	return 0;
}

你可能感兴趣的:(C,数据结构)