链表链表结构体的定义
typedef int Type;
typedef struct Node
{
struct Node* _next;
Type _data;
}Node;
typedef struct SingleList
{
Node* _head; // head: 表示链表真正的头结点,即第一个有效的数据的位置
}SingleList;
//上面的两个结构体共同组成一个链表
带头链表和不带头链表的区别:
带头结点的链表中head的数据项为空,而不带头的链表直接在头结点存入数据,那么当从头插入数据时,head需要时刻变化
综上,一般单链表都是用带头链表,比较方便操作;
链表初始化
void singleListInit(SingleList* sl){
//空链表
sl->_head = NULL;
}
打印整个链表
void singleListPrint(SingleList* sl){
Node* cur = sl->_head;
while (cur){
printf("%d ", cur->_data);
cur = cur->_next;
}
printf("\n");
}
扩展链表
Node* creatNode(Type data){
Node* node = (Node*)malloc(sizeof(Node));
node->_data = data;
node->_next = NULL;
return node;
}
头插
void singleListPushFront(SingleList* sl, Type data){
Node* node = creatNode(data);
//先判断是否为空表
if (sl->_head == NULL){
sl->_head = node;
}
else{
node->_next = sl->_head;
sl->_head = node;
}
}
头删
void singleListPopFront(SingleList* sl){
if (sl->_head){
Node* cur = sl->_head;
sl->_head = cur->_next;
free(cur);
}
}
尾插
void singleListPushBack(SingleList* sl, Type data){
Node* node = creatNode(data);
if (sl->_head == NULL)
sl->_head = node;
else{
//找到最后一个数据
// last newNode
Node* last = sl->_head;
while (last->_next){
last = last->_next;
}
//尾插
last->_next = node;
}
}
尾删
void singleListPopBack(SingleList* sl){
//找到最后一个节点,并且,修改被删除节点的前驱节点的执行
if (sl->_head){
//找到最后一个节点,遍历的过程中,更新prev
Node* prev = NULL;
Node* tail = sl->_head;
while (tail->_next){
prev = tail;
tail = tail->_next;
}
//如果删除的为头结点, 或者链表中只要一个节点
//和下面判断等价if (prev == NULL)
if (tail == sl->_head)
sl->_head = NULL;
else
prev->_next = NULL;
free(tail);
}
}
在pos 结点之后插入
void singleListInsertAfter(Node* pos, Type data){
if (pos == NULL)
return;
// pos newNode next
Node* newNode = creatNode(data);
//注意先后顺序
newNode->_next = pos->_next;
pos->_next = newNode;
}
删除pos结点之后的数据
void singleListEraseAfter(Node* pos){
Node* next;
if (pos == NULL)
return;
//pos next
next = pos->_next;
//确保next非空指针, pos->_next->_next
if (next){
pos->_next = next->_next;
free(next);
}
}
在链表中查询数据data,并返回结点
Node* find(SingleList* sl, Type data){
Node* cur = sl->_head;
while (cur){
if (cur->_data == data) {
return cur;
}
cur = cur->_next;
}
return NULL;
}
销毁链表
void singleListDestroy(SingleList* sl)
{
Node* cur = sl->_head;
while (cur){
Node* next = cur->_next;
free(cur);
cur = next;
}
}