实例讲解C++ 双链表基本操作

本文介绍了C++中的双链表,包括其概念和结构图,并通过实例展示了双链表的基本操作,如插入节点。文章详细分析了在链表中节点前插入新节点的过程。
摘要由CSDN通过智能技术生成

1.概念

  双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。

结构图如下所示:

  

  

 

2.基本操作实例

 

DoubleList.cpp

复制代码
#include "stdafx.h"
#include "DoubleList.h"
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
DoubleList::DoubleList()
{
        pDoubleListNode pDouList = NULL;
        // 创建双链表
        CreateDouList(pDouList);
        PrintDouList(pDouList);
        // 打印逆序链表
        PrintDouReverseList(pDouList);
        // 节点后插入节点
        InsertNodeAfter(pDouList);
        PrintDouList(pDouList);
        // 节点前插入节点
        InsertNodeBefore(pDouList);
        PrintDouList(pDouList);
        // 删除节点
        DeleteNode(pDouList);
        PrintDouList(pDouList);
        // 删除链表
        DeleteDouList(pDouList);
        PrintDouList(pDouList);
        system("PAUSE");
}
DoubleList::~DoubleList()
{
}
//创建双向链表
void DoubleList::CreateDouList(pDoubleListNode &head)
{
    char x;          // 定义成char型是用于输入'q'时可以退出,其实定义成int也能退出
    pDoubleListNode p, s;
    head = (pDoubleListNode)malloc(sizeof(DoubleListNode));
    head->next = NULL;
    head->prior = NULL;        // 构造头结点p
    p = head;
    printf("\n输入双向链表的元素,每输入一个元素后按回车,输入q表示结束.\n");
    fflush(stdin);   //清空输入缓冲区
    x = getchar();
    while (x != 'q')
    {
        s = (pDoubleListNode)malloc(sizeof(DoubleListNode));
        s->data = x - '0';  // 得到的是输入字符的ASCII码,减去30H就变成想要的数字
        s->next = NULL;
        s->prior = p;
        p->next = s;
        p = s;
        fflush(stdin);
        x = getchar();
    }
    if (x == 'q')
    {
        printf("双向链表构造完毕!\n");
    }
}
//打印双向链表
void DoubleList::PrintDouList(pDoubleListNode &head)
{
    pDoubleListNode p;
    printf("\n打印出双向链表数据为:\n");
    if (!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值