线性表的链式表示和实现(双向链表)

线性表的链式表示和实现(双向链表)

前言:

书中自有颜如玉,书中自有黄金屋。

参考文献:

参考《数据结构》(C语言版) 线性表的链式表示和实现P35~P37

参考博客:https://blog.csdn.net/qq_41523096/article/details/86575377

代码(详细注释)

#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef bool Status;
#define ERROR false;
#define OK true;

struct DuLNode
{
    ElemType data;  //元素值
    DuLNode *prior; //指向前一个节点的指针
    DuLNode *next;  //指向后一个节点的指针
};

DuLNode *CreateList_Head(int n) //双向链表前插法
{
    ElemType data;
    DuLNode *head, *p;
    head = (DuLNode *)malloc(sizeof(DuLNode));
    head->next = head->prior = head;
    for (int i = 0; i < n; ++i)
    {
        cin >> data;
        p = (DuLNode *)malloc(sizeof(DuLNode));
        p->data = data;
        p->prior = head;
        p->next = head->next;
        head->next->prior = p;
        head->next = p;
    }
    return head;
}

DuLNode *CreateList_Rear(int n) //双向链表尾插法
{
    ElemType data;
    DuLNode *head, *p, *rear;
    head = rear = (DuLNode *)malloc(sizeof(DuLNode));
    head->next = head->prior = head;
    rear->next = head;
    for (int i = 0; i < n; ++i)
    {
        cin >> data;
        p = (DuLNode *)malloc(sizeof(DuLNode));
        p->data = data;
        p->prior = rear;
        p->next = rear->next;
        rear->next = p;
        rear = p;
    }
    return head;
}

Status DuLinkList_Insert(DuLNode *head, int pos, ElemType e) //在pos位置插入元素e
{
    DuLNode *p = head, *s;
    int i = 0;
    while (p->next != head && i < pos - 1) //此处判断是否为末尾有所不同
    {
        p = p->next;
        ++i;
    }
    if ((p->next == head && i != pos - 1) || i > pos - 1)
        return ERROR;
    s = (DuLNode *)malloc(sizeof(DuLNode));
    s->data = e;
    s->next = p->next;
    s->prior = p;
    p->next->prior = s;
    p->next = s;
    return OK;
}

Status DuLinkList_Delete(DuLNode *head, int pos) //删除pos位置的元素
{
    DuLNode *p = head;
    int i = 0;
    while (p->next != head && i < pos) //此处判断是否为末尾有所不同
    {
        p = p->next;
        ++i;
    }
    if ((p->next == head && i != pos) || i > pos)
        return ERROR;
    p->prior->next = p->next;
    p->next->prior = p->prior;
    free(p);
    return OK;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值