小白上手写的第一个双向链表(C++)
2021-06-27 08:06
标签:node for data sem 分享图片 cout lis bsp image #include //节点 //链表类 class LinkList { LinkList::~LinkList() void LinkList::AddToTail(int x) } void LinkList::DeleteFromHead() void LinkList::DeleteFromTail() void LinkList::display() int LinkList::Num() int main() //测试用例 L.display(); cout L.Insert(2, 0); return 0; 打印结果如下: 小白上手写的第一个双向链表(C++) 标签:node for data sem 分享图片 cout lis bsp image 原文地址:https://www.cnblogs.com/c-w-l-110120/p/9652227.html
using namespace std;
struct Node
{
int data;
Node* next;
Node* prev;
};
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;
}
{
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;
}
}
{
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;
}
{
if (IsEmpty())
{
return;
}
else
{
Node* cur = head;
head = head->next;
delete cur;
}
}
{
if (IsEmpty())
{
return;
}
else
{
Node* cur = head;
while (cur->next)
{
cur = cur->next;
}
cur->prev->next = NULL;
delete cur;
}
}
{
for (Node *p = head; p != NULL; p = p->next)
{
cout data }
}
{
int count = 0;
Node*cur = NULL;
cur = head;
while (cur)
{
count++;
cur = cur->next;
}
return count;
}
{
LinkList L;
L.AddToHead(20);
L.AddToHead(10);
L.AddToTail(30);
L.AddToTail(40);
L.display();
cout cout
}
上一篇:递归算法
文章标题:小白上手写的第一个双向链表(C++)
文章链接:http://soscw.com/index.php/essay/98349.html