c++编程实现一个双向链表

自己发现在学习链表、双向链表、二叉树的时候,其实是有一定的规律的。

例如链表中节点的定义:

typedef struct node
{
	int data;
	node* next;
}Node;

双向链表中节点的定义:

typedef struct node
{
	int data;
	node* left;
	node* right;
}DDNode;

二叉树节点的定义:

typedef struct node
{
	int data;
	node* parent;
	node* left;
	node* right;
}Node;

可以看到节点定义内部的指针呈现1-2-3数目增加,关于链表的操作都是一些基本的操作,在这里不做赘述,直接上c++编程实现一个双向链表代码:

每天一点代码,冲冲冲!

/********************************************************
 *[abstract] Double direction list
 *[date]     2020/8/25 21:16
 *[author]   LowHand
 ********************************************************/

#include <iostream>
#include <cstdlib>

using namespace std;

/* This is used to create a node. */
typedef struct node
{
	int data;
	node* left;
	node* right;
}DDNode;

/********************************************************
 * Three functions are needed to create a DDList:
 * [1] CreateNode(): create and return an node.
 * [2] CreateDDList(): create DDList.
 * [3] InsertNode(); insert value.
 ********************************************************/

DDNode *CreateNode(int data)
{
	using namespace std;
	DDNode *Newnode = (DDNode*)malloc(sizeof(DDNode));
	Newnode->data = data;
	Newnode->left = Newnode->right = Newnode;

	return Newnode;
}

DDNode *CreareDDList(int head)
{
	DDNode* Newnode = (DDNode*)malloc(sizeof(DDNode));
	Newnode->data = head;
	Newnode->left = Newnode->right = Newnode;

	return Newnode;
}

// insert new nodes at the end of list and return the front node.

DDNode *InsertNode(DDNode* head, int data)
{
	DDNode *node = CreateNode(data);
	DDNode *p = head;
	DDNode *q;

	while (p != NULL)
	{
		q = p;
		p = p->right;  // here we need to notice the direction.
	}
	q->right = p;
	p->left = q;

	return head;
}
// Fight for life。
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值