首先先看双链表以及循环链表的结构图
看完了之后,差别在哪很明显了吧。下面直接上双链表的代码
// 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;
}