C语言-动态链表

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

struct LinkNode {
	int data;
	struct LinkNode* next;
};
void printList(struct LinkNode* li) {
	if (li == NULL) { return; }

	while (li->next!=NULL) {
		li = li->next;
		printf("%d ", li->data);
	}
	printf("\n");
}
struct LinkNode* newDynamicList(){
	struct LinkNode* head = (struct LinkNode*)malloc(sizeof(struct LinkNode));
	struct LinkNode* temp = head;
	int num = 0;
	while (1) {
		printf("输入节点:");
		scanf("%d", &num);
		if (num == -1) {
			break;
		}
		struct LinkNode* newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode));
		newNode->next = NULL;
		newNode->data = num;
		temp->next = newNode;
		temp = temp->next;
	}
	return head;
}

void deleteDynamicList(struct LinkNode* li) {
	if (li == NULL) { return; }
	struct LinkNode* temp = li->next;
	while (temp!=NULL) {
		struct LinkNode* next = temp->next;
		printf("free :%d", temp->data);
		free(temp);
		temp = next;
	}
	li->next = NULL;
}
void insertList(struct LinkNode* li,int posData,int newData) {
	if (li == NULL) { return; }
	struct LinkNode* previous = li;
	struct LinkNode* temp = li->next;

	while (temp != NULL) {
		if (temp->data == posData) {
			break;
		}
		previous = temp;
		temp = temp->next;
	}
	struct LinkNode* newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode));
	newNode->data = newData;
	previous->next = newNode;
	newNode->next = temp;
}
void deleteList(struct LinkNode* li, int posData)
{
	struct LinkNode* previous = li;
	struct LinkNode* temp = li->next;
	while (temp!=NULL) {
		if (temp->data == posData) {
			struct LinkNode* t = temp;
			previous->next = temp->next;
			temp = previous->next;
			free(t);
			t = NULL;
		}
		else {
			previous = temp;
			temp = temp->next;
		}
	}
}
int main(int argc, char* argv[])
{
	printf("创建链表\n");
	//创建链表
	struct LinkNode* head = newDynamicList();
	//打印链表
	printList(head);
	//插入节点
	insertList(head, 20, 1000);
	insertList(head, 30, 2000);
	insertList(head, 90, 9000);
	//打印链表
	printList(head);
	//删除指定节点
	deleteList(head,20);
	deleteList(head,30);
	deleteList(head, 40);
	deleteList(head, 50);
	//打印链表
	printList(head);
	//删除链表
	deleteDynamicList(head);
	system("pause");
	return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值