最简单的双向环形链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_31872269/article/details/79961845
// NewList.cpp : 定义控制台应用程序的入口点。
//

#include "string.h"
#include "stdlib.h"
#include <stdio.h>
// 链表节点
typedef struct _Node_
{
    int id;
    char name[256];
    _Node_ * pre;
    _Node_ * next;
}Node;
// 链表头信息
typedef struct _ListHead_
{
    int numNode;
    Node * pNode;

}ListHead;
// 尾插法
int tailInsterHeadList(ListHead * pListHead, Node * pNode)
{
    if (pListHead->pNode)
    {
        Node * p = NULL;
        for (p = pListHead->pNode; p->next != pListHead->pNode; p = p->next)
        {
        }
        pNode->pre = p;
        pNode->next = p->next;
        p->next = pNode;
        pListHead->pNode->pre = pNode;
    }
    else
    {
        pListHead->pNode = pNode;
        pNode->next = pNode;
        pNode->pre = pNode;
    }

    pListHead->numNode++;
    return 0;
}

int initHead(ListHead * pListHead)
{

    pListHead->numNode = 0;
    pListHead->pNode = NULL;
    return 0;
}
int main()
{
    ListHead * pListHead = (ListHead *)calloc(sizeof(ListHead), 1);
    char * pName[10] = { "a", "b", "c", "d", "e", "f","g","h", "i", "j" };
    for (int i = 0; i < 10; i++)
    {
        Node * pNode = (Node *)calloc(1, sizeof(Node));
        pNode->id = i;
        pNode->next = NULL;
        pNode->pre = NULL;

        memcpy(pNode->name, pName[i], sizeof(pName[i]));
        tailInsterHeadList(pListHead, pNode);
    }

    printf("顺序打印数据 \n");
    Node * p = NULL;
    for (p = pListHead->pNode; p->next != pListHead->pNode; p = p->next)
    {
        printf("%s \n", p->name);
    }
    printf("%s \n", p->name);

    printf("逆序打印数据 \n");
    for (p = pListHead->pNode->pre; p->pre != pListHead->pNode->pre; p = p->pre)
    {
        printf("%s \n", p->name);
    }
    printf("%s \n", p->name);
    return 0;
}

阅读更多

没有更多推荐了,返回首页