双向循环链表

// 循环双链表:在双链表的基础上让尾节点的next指向头节点,头节点的头指针指向尾节点

#include <stdio.h>
#include <stdlib.h>
// 链表构造
typedef struct Node
{
    int data;
    struct  Node* pre;//头指针
    struct Node* next;//尾指针   
}Node;

// 初始化
Node* initList()
{
    Node* list = (Node*)malloc(sizeof(Node));
    list->data = 0;
    list->pre = list;
    list->next = list;//头指针和尾指针都指向自身
    return list;
}

// 头插
void headInsert(Node* list, int data)
{
    // 开辟空间,创建节点
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = list->next;//对新节点头尾指针操作
    node->pre = list;
    // 这里不需要进行判断,因为链表循环,所以头节点后面还有节点,只不过还是头节点罢了
    list->next->pre = node;
    list->next = node; 
    list->data++;
}
// 尾插
void tailInsert(Node* list, int data)
 {
    //  开辟空间,创建节点
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    Node* current = list->next;//指向第一个节点
    // 从第一个节点开始遍历,找到尾节点
    while(current->next != list)
    {
        current = current->next;
    }
    node->next = current->next;//对新节点的头尾指针进行链接
    node->pre = current;

    list->pre = node;//对指向尾节点的指针进行修改
    current->next = node;
    list->data++;

 }

//  删除
void delete(Node* list, int data)
{
    // Node* pre = list;不需要保存前一个节点了,因为current有头指针,可以找到前一个节点
    Node* current = list->next;
    while (current != list) 
    {
        if (current->data == data)
        {
            current->pre->next = current->next;//调整前一个指针next指向
            current->next->pre = current->pre;//调整后一个指针pre指向
            free(current);
            current = NULL;
            printf("已删除!\n");
            list->data--;
            return;
        }
        current = current->next;
    }
    printf("没找到!\n");
}

// 打印
void printList(Node* list)
{
    Node* current = list->next;//指向第一个头节点
    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);
    // 打印
    printList(list);

     // 尾插
    tailInsert(list, 4);
    tailInsert(list, 5);
    tailInsert(list, 6);
    // 打印
    printList(list);

    delete(list, 3);
    delete(list, 5);
    printList(list);
    return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值