C 语言 单链表操作

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

#include<memory.h>

typedef struct list_node
{
int data;                     //数据域,用来存放数据; 
struct list_node *next;       //定义一个结构体指针,指向下一次与当前节点数据类型相同的节点  

}list_single;


/***********************************************************************************************************************
* 创建单链表的一个节点
***********************************************************************************************************************/
list_single *creat_single_list_node(int value)
{
list_single *node = NULL;
node = (list_single *)malloc(sizeof(list_single));
if (node == NULL){
printf("malloc fair !\n");
}
else{
node->data = value;
node->next = NULL;
}
return node;

}


/***********************************************************************************************************************
* 获取单链表的长度,遍历链表
***********************************************************************************************************************/
int get_single_list_len(list_single *pHead)
{
    int len = 0;
list_single * node = NULL;
node = pHead->next;
while (node != NULL){
len++;
node = node->next;
}
return len;
}


/***********************************************************************************************************************
* 删除单链表中的某个节点
***********************************************************************************************************************/
bool delete_single_list_node(list_single *pHead, int position, int *val)
{
int i = 0;
list_single * node = NULL;
list_single * del_node = NULL;
node = pHead;
while ((node != NULL) && (i < position - 1)){
node = node->next;
i++;
}
if ((node == NULL) || i > (position - 1)){
printf("the single list is NULL.\n");
return false;
}
del_node = node->next;
*val = del_node->data;
node->next = del_node->next;
free(del_node);
del_node = NULL;
return true;
}


/***********************************************************************************************************************
* 删除整个单链表
***********************************************************************************************************************/
void delete_all_single_list(list_single *pHead)
{
int i = 0;
list_single * temp_node = NULL;
list_single * del_node = NULL;
del_node = pHead->next;
pHead->next = NULL;
while (del_node != NULL)
{
temp_node = del_node->next;
free(del_node);
del_node = temp_node;
}
}

猜你喜欢

转载自blog.csdn.net/a805101628/article/details/80349550
今日推荐