小白上手写的第一个双向链表(C++)

2021-06-27 08:06

阅读:573

标签:node   for   data   sem   分享图片   cout   lis   bsp   image   

#include
using namespace std;

//节点
struct Node
{
int data;
Node* next;
Node* prev;
};

//链表类

class LinkList

{
private:
Node * head;
public:
void AddToHead(int x);//头部插入新元素
void AddToTail(int x);//尾部插入新元素
void DeleteFromHead();//删除头部一个元素
void DeleteFromTail();//删除尾部一个元素
void display();//打印链表
int GetNum(int x);//获得指定位置的元素
void Insert(int pos, int Num);//在指定位置插入新元素
int Num();//返回链表的长度
bool IsEmpty();//判断链表是否为空
~LinkList();//析构函数,释放空间。
};
void LinkList::Insert(int pos, int N)
{
if (pos == Num())
{
AddToTail(N);
return;
}
Node *p = head;
for (int i = 0; i next)
{
;
}
Node *cur = new Node;
cur->data = N;
p->next->prev = cur;
cur->next = p->next;
p->next = cur;
cur->prev = p;
}

LinkList::~LinkList()
{
while (head)
{
Node*p = head;
head = head->next;
delete p;
}
}
int LinkList::GetNum(int x)
{
Node *p = head;
for (int i = 0 ; i next)
{
;
}
return p->data;
}
bool LinkList::IsEmpty()
{
return head == NULL ? true : false;
}
void LinkList::AddToHead(int x)
{
Node* p = new Node;
p->data = x;
p->prev = NULL;
p->next = NULL;
if (IsEmpty())
{
p->prev = head;
head = p;
}
else
{
p->next = head;
head->prev = p;
head = p;
}
}

void LinkList::AddToTail(int x)
{
Node* p = new Node;
p->data = x;
p->prev = NULL;
p->next = NULL;
if (IsEmpty())
{
p->prev = head;
head = p;
}
else
{
Node * cur = NULL;
cur = head;
while (cur->next)
{
cur = cur->next;
}
cur->next = p;
p->prev = cur;

}
}

void LinkList::DeleteFromHead()
{
if (IsEmpty())
{
return;
}
else
{
Node* cur = head;
head = head->next;
delete cur;
}
}

void LinkList::DeleteFromTail()
{
if (IsEmpty())
{
return;
}
else
{
Node* cur = head;
while (cur->next)
{
cur = cur->next;
}
cur->prev->next = NULL;
delete cur;
}
}

void LinkList::display()
{
for (Node *p = head; p != NULL; p = p->next)
{
cout data }
}

int LinkList::Num()
{
int count = 0;
Node*cur = NULL;
cur = head;
while (cur)
{
count++;
cur = cur->next;
}
return count;
}

int main()
{

//测试用例
LinkList L;
L.AddToHead(20);
L.AddToHead(10);
L.AddToTail(30);
L.AddToTail(40);

L.display();

cout L.Insert(2, 0);
L.display();
cout cout

return 0;
}

 打印结果如下:

技术分享图片

 

小白上手写的第一个双向链表(C++)

标签:node   for   data   sem   分享图片   cout   lis   bsp   image   

原文地址:https://www.cnblogs.com/c-w-l-110120/p/9652227.html

上一篇:递归算法

下一篇:Python内置函数__slots__


评论


亲,登录后才可以留言!