数据结构c语言代码实现单链表

126 阅读1分钟

关于数据结构,单链表一定是最简单的了。

那么今天让我们一起来看看如何用c语言实现单链表尼?废话不多说,直接上代码。

这是分装的代码,直接合并即是全部代码。

  1. 声明头文件,结构体
    

#include<stdio.h>

#include<stdlib.h>

#include<assert.h>

typedef struct Node

{

int data
struct Node* next;

}Node;

  1.   初始化链表
    

Node* initList()

{

Node* list = (Node*)malloc(sizeof(Node));
assert(list);            //assert作用:如果开辟空间失败,直接报错
list->data = 0;        //以头结点的数据域来作为元素个数
list->next = NULL;      
return list;
    

}

  1.  头插法添加
    

void headInsert(Node* list,int data)

{

Node* node = (Node*)malloc(sizeof(Node));
assert(node);                       //assert作用:如果开辟空间失败,直接报错
node->data = data;
node->next = list->next;
list->next = node;
list->data++;						//表示链表长度加一

} 4. 尾插法添加 5.
void tailInsert(Node* list,int data)

{

Node* head = list;					 //保存头结点地址
Node* node = (Node*)malloc(sizeof(Node));
assert(node);                        //assert作用:如果开辟空间失败,直接报错
node->data = data;
node->next = NULL;
list=list->next;
while (list->next != NULL)
{
	list = list->next;
}
list->next = node;
head->data++;						//长度加一

}

  1.   随便一位置删除元素
    

void delete(Node* list, int data)

{

Node* pre = list;
Node* current = list->next;						//定义前后两个指针
while (current != NULL)
{
	if (current->data == data)
	{
		pre->next = current->next;
		break;                              //删除一个,如果删重复元素去掉break即可
	}
	pre = current;
	current= current->next;
}
list->data--;                               //元素长度减一
free(current);

}

  1.   打印链
    

void printList(Node* list)

{ list = list->next; //跳过头结点 while (list) { printf("%d->", list->data); list = list->next; } printf("NULL\n"); }

  1.    主函数
    

int main()

{ Node* list = initList(); headInsert(list, 1); headInsert(list, 2); headInsert(list, 3); tailInsert(list, 1); tailInsert(list, 2); tailInsert(list, 3); delete(list, 3); printList(list); //这是测试调用函数,可自行更改。 return 0; } 如有错误,欢迎大家批评改正。