0
点赞
收藏
分享

微信扫一扫

单链表C语言实现


单链表


单链表C语言实现_链表


1.设计节点:

struct  Node{
int data;
struct Node *next;
};

2.创建节点

单链表C语言实现_链表_02


//1.创建节点
struct Node *create(int data){
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}


3.插入数据

单链表C语言实现_数据结构_03


//2.插入数据
bool insert(struct Node *head, struct Node* new)
{
if(head == NULL || new == NULL) return false;
new->next = head->next;
head->next = new;
return true;}


4.遍历链表

单链表C语言实现_数据结构_04


//3.遍历链表
void display(struct Node *head)
{
if(head==NULL || head->next==NULL) return ; //链表上没有数据
head = head->next;
while(head)
{
printf("%d ", head->data);
head = head->next;
}printf("\n");
}

5.删除节点

单链表C语言实现_插入数据_05


4.删除节点
//4.删除节点
bool delete(struct Node* head, int data)
{
//判断链表
if(head==NULL || head->next == NULL) return false;
//查找data这个数据所在节点的上一个节点
while(head->next != NULL)
{
if(head->next->data == data)
{
//定义遍历保存要删除的节点
struct Node* p = head->next;
head->next = p->next;
p->next = NULL;
free(p);
break;
}else head = head->next;
}
return true;
}


6.尾插入

单链表C语言实现_链表_06

bool insert_tail(struct Node* head, struct Node* new)
{
if(head == NULL || new == NULL) return false;
//遍历到链表尾部
struct Node * p = head;
while(p->next){
p = p->next;
}
p->next = new;
return true;
}

举报

相关推荐

0 条评论