0
点赞
收藏
分享

微信扫一扫

手撕数据结构—单链表

茗越 2023-06-04 阅读 72

相关知识点

1.线性表

2.顺序表

        分配一块连续的内存去存放这些元素,例如编程语言中的素组。

3.链表

        内存是不连续的,元素会各自被分配一块内存,内存和内存之间用指针进行相连。

 本文重点对单链表的相关操作进行讲解

相关操作

1.定义数据结构

typedef struct Node{

	int data;
	struct Node* next;
}Node;

2.插入

2.1头插法

                

        将头指针指向的节点赋值给新结点中next指向的节点,再将头结点的next从新指向node

//头插法
void headInsert(Node* list,int data){

	Node* node =(Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = list->next;
	list->next = node;
	list->data++;
}

2.2尾插法

          

        创建一个新结点,将值传入其中,再将新结点的next—>NULL,最后通过遍历找到以前的尾元素,将尾元素的next指向该元素。

//尾插法
void tailInsert(Node* list,int data){

	Node* head = list;
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = NULL;
	list = list->next;

	while(list->next){
		list = list->next;
	}
	list->next = node;
	head->data++;
}

3.删除

                 

        删除指定节点时,要注意指针指向的节点是否为空,之后便是进行扫描与交换数据域,再之后就是进行断开释放空间等操作

void delete(Node* list,int data){

	Node* pre = list;
	Node* current = list->next;

	while(current){
		
		if(current->data==data){
		
			pre->next = current->next;
			free(current);
			break;
		}
		pre = current;
		current = current->next;
	}
	list->data--;
}

完整代码

#include<stdio.h>
#include<stdlib.h>//开辟空间的头文件

//定义数据结构
typedef struct Node{

	int data;
	struct Node* next;
}Node;

//初始化头节点
Node* initList(){

	Node* list =(Node*)malloc(sizeof(Node));
	list->data = 0;
	list->next = NULL;
	return list;

}

//头插法
void headInsert(Node* list,int data){

	Node* node =(Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = list->next;
	list->next = node;
	list->data++;
}

//尾插法
void tailInsert(Node* list,int data){

	Node* head = list;
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = NULL;
	list = list->next;

	while(list->next){
	
		list = list->next;
	}
	list->next = node;
	head->data++;
}

//删除操作
void delete(Node* list,int data){

	Node* pre = list;
	Node* current = list->next;

	while(current){
		
		if(current->data==data){
		
			pre->next = current->next;
			free(current);
			break;
		}
		pre = current;
		current = current->next;
	}
	list->data--;
}

//遍历操作
void printList(Node* list){
	list = list->next;
	while(list){
	
		printf("%d",list->data);
		list = list->next;
	}
	printf("\n");
}

int main(){
	Node* list = initList();
	headInsert(list,1);
	headInsert(list,2);
	headInsert(list,3);
	headInsert(list,4);
	headInsert(list,5);
	tailInsert(list,6);
	tailInsert(list,7);
	tailInsert(list,8);
	tailInsert(list,9);
	tailInsert(list,10);
	delete(list,5);
	delete(list,10);
	delete(list,3);
	printList(list);
	return 0;

}
举报

相关推荐

0 条评论