数据结构纯属新手,小白一枚,欢迎批评指正!
下面这个图是接下来要实现的单循环链表!
直接上代码OVO!
定义结构体
typedef struct Node {
int data; //数据域
struct Node* next; //指针域
}Node;
单循环链表跟单链表类似只有数据域和指向下一个结点的指针域,不过尾结点的指针域指向第一个结点。
创建链表
//创建单循环链表
Node* initList() {
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
return L;
}
头插法
//头插法
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
L->data++;
}
尾插法
//尾插法
void tailInsert(Node* L,int data) {
Node* n = L;
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
n = L->next;
while (n->next != L) {
n = n->next;
}
node->next = n->next;
n->next = node;
L->data++;
}
删除结点
//删除结点
int deleteList(Node* L, int data) {
Node* node = L->next;
Node* preNode = L;
while (node != L) {
if (node->data == data) {
preNode->next = node->next;
L->data--;
free(node);
return TRUE;
}
preNode = node;
node = node->next;
}
return FALSE;
}
遍历链表
//遍历链表
void printList(Node* L) {
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
全部代码:
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct Node {
int data;
struct Node* next;
}Node;
//创建单循环链表
Node* initList() {
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
return L;
}
//头插法
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
L->data++;
}
//尾插法
void tailInsert(Node* L,int data) {
Node* n = L;
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
n = L->next;
while (n->next != L) {
n = n->next;
}
node->next = n->next;
n->next = node;
L->data++;
}
//删除结点
int deleteList(Node* L, int data) {
Node* node = L->next;
Node* preNode = L;
while (node != L) {
if (node->data == data) {
preNode->next = node->next;
L->data--;
free(node);
return TRUE;
}
preNode = node;
node = node->next;
}
return FALSE;
}
//遍历链表
void printList(Node* L) {
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
int main(void) {
Node* L=initList();
headInsert(L,1);
headInsert(L,2);
headInsert(L,3);
headInsert(L,4);
headInsert(L,5);
tailInsert(L,6);
tailInsert(L,7);
deleteList(L,1);
printList(L);
return 0;
}
运行截图:
总结
单循环链表是单链表的另一种形式,其结构特点链表中最后一个结点的指针域不再是结束标记,而是指向整个链表的第一个结点,从而使链表形成一个环。.
和单链表相同,单循环链表也有带头结点结构和不带头结点结构两种,带头结点的循环单链表实现插入和删除操作较为方便。.