单链表的创建(带头节点&不带头节点)
程序员文章站
2022-03-15 18:33:44
...
#include <iostream>
using namespace std;
//创建链表类节点
class ListNode
{
public:
//无参构造函数
ListNode() { next = nullptr; }
//有参构造函数
ListNode(int x)
{
val = x;
next = nullptr;
}
int val;
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
{
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;
p = p->next;
}
return head;
}
//递归访问链表
void traverse(ListNode * p)
{
if (!p)
{
cout << endl;
return;
}
cout << p->val << " ";
traverse(p->next);
}
int main()
{
ListNode * head = NoHead();
cout << "NoHead" << endl;
traverse(head);
head = WithHead();
cout << "WithHead" << endl;
traverse(head->next);
system("pause");
return 0;
}
下一篇: 增速放缓,互联网巨头投资“养家”