#include <stdio.h>
#include <stdlib.h>
// 单循环链表节点定义
struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
};
// 创建仅有尾指针的单循环链表
struct Node* createListWithTail(int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = newNode; // 将next指针指向自身,形成循环
return newNode; // 返回头节点指针
}
// 在仅有尾指针的单循环链表的末尾添加节点
void appendToListWithTail(struct Node** tail, int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = (*tail)->next; // 将新节点的next指针指向头节点
(*tail)->next = newNode; // 将尾节点的next指针指向新节点
*tail = newNode; // 更新尾指针为新节点
}
// 遍历并打印仅有尾指针的单循环链表
void printListWithTail(struct Node* tail) {
struct Node* current = tail->next; // 从头节点开始遍历
do {
printf("%d ", current->data);
current = current->next;
} while (current != tail->next); // 遍历直到回到头节点
}
// 创建仅有头指针的单循环链表
struct Node* createListWithHead(int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = newNode; // 将next指针指向自身,形成循环
return newNode; // 返回头节点指针
}
// 在仅有头指针的单循环链表的末尾添加节点
void appendToListWithHead(struct Node* head, int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head; // 将新节点的next指针指向头节点
// 遍历链表,找到最后一个节点
struct Node* current = head;
while (current->next != head) {
current = current->next;
}
current->next = newNode; // 将最后一个节点的next指针指向新节点
}
// 遍历并打印仅有头指针的单循环链表
void printListWithHead(struct Node* head) {
struct Node* current = head;
do {
printf("%d ", current->data);
current = current->next;
} while (current != head); // 遍历直到回到头节点
}
int main() {
// 创建并操作仅有尾指针的单循环链表
struct Node* tailList = createListWithTail(1);
appendToListWithTail(&tailList, 2);
appendToListWithTail(&tailList, 3);
printListWithTail(tailList);
printf("\n");
// 创建并操作仅有头指针的单循环链表
struct Node* headList = createListWithHead(1);
appendToListWithHead(headList, 2);
appendToListWithHead(headList, 3);
printListWithHead(headList);
return 0;
}
仅有尾指针的单循环链表和仅有头指针的单循环链表之间的区别:
1. 仅有尾指针的单循环链表:
- 这种类型的链表只有一个指针,即尾指针,用于指向链表的尾部节点。
- 在插入和删除节点时,由于只需要修改尾节点的指针,所以操作相对简单,时间复杂度为O(1)。
- 但在访问链表中的节点时,需要从尾节点开始遍历整个链表,直到回到尾节点,时间复杂度为O(n),其中n是链表的长度。
2. 仅有头指针的单循环链表:
- 这种类型的链表只有一个指针,即头指针,用于指向链表的头部节点。
- 在插入和删除节点时,需要先遍历链表找到尾节点,然后再进行操作,时间复杂度为O(n)。
- 在访问链表中的节点时,只需要从头节点开始遍历整个链表,直到回到头节点,时间复杂度为O(n),其中n是链表的长度。
因此,仅有尾指针的单循环链表在插入和删除节点时更加高效,但在访问节点时较慢;而仅有头指针的单循环链表在插入和删除节点时较慢,但在访问节点时更加高效。