前言
单循环链表
顾名思义,它是一个循环链接
的表,当我们把单链表的尾节点指向头节点
时,就形成了一个循环,此时就是一个单循环链表。
代码
单链表的增、删、查。
// 单循环链表:指针指向头节点
#include <stdio.h>
#include <stdlib.h>
// 链表构造
typedef struct Node
{
int data;
struct Node* next;
}Node;
// 初始化
Node* initList()
{
// 开辟空间,创建节点
Node* ptr = (Node*)malloc(sizeof(Node));
ptr->data = 0;
ptr->next = ptr;//自己指向自己
}
// 头插法
void headInsert(Node* list, int data)
{
// 开辟空间,创建节点
Node* node = (Node*)malloc(sizeof(Node));
node->data =data;//传数据
node->next = list->next;//让新建节点指向头节点
list->next = node;//头节点指向新建节点
list->data++;//头节点data用来记录后面节点数量
}
// 尾插法
void tailInsert(Node* list, int data)
{
// 开辟空间,创建节点
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;//传数据
node->next = list;//指向头节点
// 找到最后一个节点,在最后一个节点后面插入
Node* current = list->next;//第一个节点,从此节点开始遍历
while (current->next != list)//最后一个节点的特点:它的next为头节点
{
current=current->next;//移动到下一个节点
}
current->next = node;//原尾节点指向新的尾节点
list->data++;//节点数量+1
}
// 删除操作
void delete(Node* list, int data)
{
Node* pre = list;//用来移动节点的前一个节点
Node* current = list->next;//第一个节点,用来移动
while (current != list)
{
if (current->data == data)//匹配到相应节点
{
pre->next = current->next;//让前一个节点指向相应节点的后续节点
free(current);//释放相应节点
current = NULL;
list->data--;//节点数量-1
printf("删除成功!\n");
return;
}
pre = current;//不匹配往后移动
current = current->next;
}
printf("没找到!\n");
}
// 打印链表
void printList(Node* list)
{
Node* current = list->next;//current指向第一个节点
// 从第一个节点开始遍历
while (current != list)//直到遇到头节点才停止遍历
{
printf("%d->", current->data);
current = current->next;
}
printf("NULL\n");
}
int main(int argc, char const *argv[])
{
// 单链表初始化
Node* list = initList();
headInsert(list, 1);
headInsert(list, 2);
headInsert(list, 3);
headInsert(list, 4);
headInsert(list, 5);
printList(list);
tailInsert(list, 6);
tailInsert(list, 7);
tailInsert(list, 8);
tailInsert(list, 9);
tailInsert(list, 10);
printList(list);
delete(list, 4);
delete(list, 10);
// delete(list, 11);
printList(list);
return 0;
}