C语言链表 应用总结

前言

每次面试的时候,面试官都会问你,会链表不(显得很高逼格)?掌握链表的创建、插入、删除、修改、清空。你会发现,其实链表就那么回事。

几个概述

链表可以动态分配内存。
链表一般有一个头指针,一般以head来表示,存放的是一个地址。
链表节点分为两类:头节点、一般节点。

创建链表

1.创建链表结构体
在这里插入图片描述

typedef struct LinkList {
	uint16_t count;
	struct LinkList * next;
}LinkList;

2. 生成一个链表的头指针,仅仅(just!)是一个地址;
LinkList* list_head=NULL;
3.插入链表节点。
在头指针处插入新节点。一般情况下,插入节点时,应该看是否已经有该节点。
在这里插入图片描述
普通版:

void insert_list(LinkList* list_node)
{
	list_node ->next= list_head;
	list_head= list_node;
}

升级版:
查找链表是否已经存在该节点,从head开始查找到末尾。

uint8_t insert_Listnode(LinkList* list_node)
{
	struct LinkList * currentNode =list_head;
	while(currentNode)
   {
	if(currentNode ==list_node) return 1;
    else 
     currentNode = currentNode ->next;
   }
	list->next= list_head;
	list_head =list;
    return 0;
}

删除链表节点。

把前节点的指针域越过要删除的节点指向下下个节点。即:p->next = p->next->next;然后放出q节点的空间,即free(q);
在这里插入图片描述

uint8_t detel_ListNode(struct LinkList* listNode)
{
	if(listNode== list_head)
	{
		list_head=list_head->next;
		return 0;
  }
	struct LinkList * currentNode =list_head;
	while(currentNode)
  {
    	if(currentNode ->next==list_node)
      {
    	currentNode ->next=list_node->next;
        return 0;
      }
    else 
      currentNode =currentNode ->next;
   }
   return 1;
}

获取链表长度

int list_Length(LinkList *listHead)
{
   int tempLength;
   LinkList *currentNode=listHead;
   while(!currentNode)
   {
	 tempLength++;
	 currentNode=currentNode->next;
   }
  return tempLength;
}
发布了49 篇原创文章 · 获赞 76 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/fengweibo112/article/details/88538376