双向链表的创建(带头节点&不带头节点)
程序员文章站
2022-03-16 08:52:55
...
#include <iostream>
using namespace std;
//创建链表类节点
class ListNode
{
public:
//无参构造函数
ListNode()
{
pre = nullptr;
next = nullptr;
}
//有参构造函数
ListNode(int x)
{
val = x;
pre = nullptr;
next = nullptr;
}
int val;
ListNode* pre;
ListNode* next;
};
//不带头节点的双向链表链表创建
ListNode * NoHead()
{
ListNode * head = nullptr;
ListNode * p = nullptr;
for (int i = 0; i < 10; i++)
{
ListNode * temp = new ListNode(i);
if (!head)//若第一次赋值,head为空
{
head = temp;
p = temp;
}
else
{
temp->pre = p;
p->next = temp;
p = p->next;
}
}
return head;
}
//带头节点的双向链表链表创建
ListNode * WithHead()
{
ListNode * head = new ListNode;
ListNode * p = head;
for (int i = 10; i < 20; i++)
{
ListNode * temp = new ListNode(i);
p->next = temp;
temp->pre = p;
p = p->next;
}
return head;
}
//访问链表
void Visit(ListNode * head)
{
ListNode * p = head;
while (p->next)
{
cout << p->val << " ";
p = p->next;
}
if (p == head || !p->next)//访问头部第一个节点,或者,尾部最后一个节点
cout << p->val << endl;
//带头节点的从后往前循环的时候会访问头节点
while (p!=head)//保证最后一个输出的是带值的节点
{
cout << p->val << " ";
p = p->pre;
}
if (p == head || !p->next)
cout << p->val << endl;
}
int main()
{
ListNode * head = NoHead();
cout << "NoHead" << endl;
Visit(head);
head = WithHead();
cout << "WithHead" << endl;
Visit(head->next);
system("pause");
return 0;
}
下一篇: C++实现带头节点的双向循环链表模板