双向链表

#include <iostream>
#include <stdio.h>
using namespace std;

typedef struct node
{
	int date;
	struct node *next;
	struct node *prev;
}Node;

class DLLNode
{
private:
	Node *head;
public:
	DLLNode()
	{
		head = new Node;
		head->next = nullptr;
		head->prev = nullptr;
		head->date = 0;
	}

	~DLLNode()
	{
		Node *p = nullptr;
		while(head->next != nullptr)
		{
			p = head->next->next;
			delete head->next;
			head->next = p;
		}
		delete head;
	}

	int GetLength()
	{
		return head->date;
	}

	bool empty()
	{
		if (head->date == 0)
		{
			return true;
		}
		else
			return false;
	}

	Node* create(int date)
	{
		Node* node = new Node;
		node->date = date;
		node->next = nullptr;
		node->prev = nullptr;
		return node;
	}

	void HeadInsertNode(int date)
	{
		Node *p = create(date);
		Node *q = head->next;
		p->prev = head;
		p->next = q;
		if (q == nullptr)
		{
			head->next = p;
			head->date++;
			return;
		}
		q->prev = p;
		head->next = p;
		head->date++;
	}

	void EndInsertNode(int date)
	{
		Node *q = create(date);
		Node *p = head;
		while(p->next != nullptr)
		{
			p = p->next;
		}
		q->prev = p;
		q->next = nullptr;
		p->next = q;
		head->date++;
	}

	void IndexInsertNode(int n , int date)
	{
		if (n <= head->date && n>=1)
		{
			Node *q = create(date);
			Node *p = head;
			for (int i = 0; i < n-1; ++i)
			{
				p = p->next;
			}
			q->prev = p;
			q->next = p->next;
			p->next->prev = q;
			p->next = q;
			head->date++;
		}
		else
			cout << "数值越界" << endl;
	}

	void DeleteIndexNode(int n)
	{
		if (n <= head->date && n >= 1)
		{
			Node *p = head;
			for (int i = 0; i < n-1; ++i)
			{
				p = p->next;
			}
			Node *q = p->next;
			p->next = q->next;
			q->next->prev = p;
			delete q;
			head->date--;
		}
		else
			cout << "数值错误" << endl;
	}

	void print()
	{
		Node *p = head;
		while(p->next != nullptr)
		{
			//cout << "ddd" << endl;
			p = p->next;
			cout << p->date << ' ';
		}
		cout << endl;

		cout << "reverse" << endl;

		while(p != head)
		{
			cout << p->date << ' ';
			p = p->prev;
		}
		cout << endl;
	}
	
};

int main()
{
	DLLNode L;
	for (int i = 0; i < 10; ++i)
	{
		L.EndInsertNode(i);
		//printf("0000\n");
	}
	L.print();
	cout << "IndexInsertNode" << endl;
	L.IndexInsertNode(1,10);
	L.print();

	cout << "delete" << endl;
	L.DeleteIndexNode(7);
	L.print();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值