【数据结构】单链表的基本操作
发布时间:2020-12-15 05:57:58 所属栏目:安全 来源:网络整理
导读:一、单链表基本概念 单链表是一种链式存取的数据结构 ,用一组地址任意的存储单元存放线性表中的数据 元素 。 二、单链表的基础用法 这里我们先讲一些简单的、基础的用法 如初始化,销毁,插入元素,求链表长度,打印链表以及链表的销毁 除此之外,链表还可
一、单链表基本概念单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。 二、单链表的基础用法这里我们先讲一些简单的、基础的用法 如初始化,销毁,插入元素,求链表长度,打印链表以及链表的销毁 除此之外,链表还可以有查找元素,指定位置插入,指定位置删除等用法 三、代码块各部分的单独代码块:结构体:typedef struct Node { DataType data; struct Node *Next; }LNode,*pNode,*LinkList; 链表初始化:int InitList(LinkList *head)//链表的初始化,h为头指针 { assert(head); *head=(LinkList)malloc(sizeof(LNode));//动态内存申请 if(!head) { printf("Error!"); return 1; } return 0; } 根据位置插入元素:int InsertList(LinkList head,int nPos,int data)//根据位置插入一个节点 { assert(head); pNode cur = head,q; int i = 0; while(cur && i < nPos-1) { cur = cur->Next; i++; } if(!cur||i>nPos) { return 1; } q = (pNode)malloc(sizeof(LNode)); if(!q) { return 2; } q->data = data; cur->Next = NULL; q->Next = cur->Next; cur->Next = q; return 0; } 求链表的长度:int ListLength(LinkList head)//求链表的长度 { assert(head); pNode cur=head; int total=0; while(cur)//当节点不为空 { cur = cur->Next;//指向下一个节点 total++; } return total;//返回链表的长度 } 打印链表:void TraveList(LinkList head)//遍历链表 { assert(head); pNode cur = head->Next; while(cur != NULL) { printf("t %dn",cur->data); cur = cur->Next; } } 链表的销毁:void DestroyList(LinkList head) { assert(head); pNode cur; cur = head->Next; while (cur != NULL) { pNode del = cur; cur = cur->Next; free(del); del = NULL; } head->Next = NULL; }
|