双链表以及循环链表的基本操作

首先先看双链表以及循环链表的结构图




看完了之后,差别在哪很明显了吧。下面直接上双链表的代码

// DoubleList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

struct DList
{
	double value;
	DList* prior;
	DList* next;
	/*
	DList(double value,DList* prior,DList* next)
	{
		this->value   = value;
		this->prior  = prior;
		this->next   = next;
	}
	*/
};

//头插法
DList* CreateDListByHead()
{
	int num = 10;
	//DList* head = new DList(NULL,NULL,NULL);
	DList* head = new DList;
	head->next = head->prior = NULL;
	for (int i = 1; i < num; i++)
	{
		//DList* list = new DList(i,head,head->next);
		DList* list = new DList;
		list->value = i;
		list->prior = head;
		list->next = head->next;
		head->next = list;
		if (head->next != NULL)//如果不是第一次插入,要注意下
		{
			head->next->prior = list;
		}
		
	}
	
	return head;
}

//尾插法
DList* CreateListByTail()
{
	DList* head,*tail;
	head = tail = new DList;
	int num = 10;
	for (int i = 1; i < num; i++)
	{
		DList* node = new DList;
		node->value = i;
		node->prior = tail;
		tail->next = node;
		tail = node;
		node->next = NULL;
	}

	return head;
}

int GetListLen(DList* head)
{
	int len = 0;
	DList* node = head->next;
	while (node)
	{
		len++;
		node = node->next;
	}
	return len;
}


DList* GetListPointByIndex(DList* head,int index)
{
	if (index < GetListLen(head))
	{
		int num = 1;
		DList* l = head->next;
		while (l)
		{
			if (num == index)
			{
				return l;
			}
			num++;
			l = l->next;
		}
	}
	else
	{
		return NULL;
	}

}

//插入
void InsertNode(DList* head,int position,int value)
{
	if (position < 0 || position > GetListLen(head))
	{
		cout<<"非法插入"<<endl;
		return;
	}
	DList* node = new DList;
	node->value = value;
	if (position == 0)//插在第一个位置
	{
		node->next = head->next;
		node->prior = head;
		head->next->prior = node;
		head->next = node;
	} 
	else
	{
		DList* nowNode = GetListPointByIndex(head,position);
		node->next = nowNode->next;
		node->prior = nowNode;
		nowNode->next->prior = node;
		nowNode->next = node;
	}
}

void DelListNode(DList* head,int position)
{
	if (position <= 0 || position > GetListLen(head))
	{
		cout<<"非法删除"<<endl;
		return;
	}
	DList* nowNode = GetListPointByIndex(head,position);
	nowNode->prior->next = nowNode->next;
	nowNode->next->prior = nowNode->prior;
}

//打印链表
void PrintList(DList* head)
{
	DList* node = head->next;
	while (node)
	{
		cout<<node->value<<endl;
		node = node->next;
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	//DList* head = CreateDListByHead();
	DList* head = CreateListByTail();
	InsertNode(head,0,5);
	DelListNode(head,2);
	PrintList(head);
	cout<<"长度"<<GetListLen(head)<<endl;
	system("pause");
	return 0;
}


下面贴上一写参考文章:

数据结构学习笔记(五)双链表、循环链表的算法操作

循环双链表
双链表

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值