带头节点链表的基本代码
时间: 2023-05-26 14:04:37 浏览: 62
```c++
#include <iostream>
using namespace std;
//定义链表结点
struct ListNode
{
int val;//结点值
ListNode *next;//指向下一个结点的指针
ListNode(int x) : val(x), next(NULL) {}//结构体的构造函数
};
//创建链表
ListNode* createList(int arr[], int len)
{
ListNode *dummy = new ListNode(0);//创建头节点
ListNode *p = dummy;//p指向头节点
for(int i = 0; i < len; i++)
{
ListNode *node = new ListNode(arr[i]);//创建新节点
p->next = node;//将新节点连接到p的后面
p = p->next;//移动p
}
p = dummy->next;//将p指向第一个结点
delete dummy;//释放头节点
return p;//返回链表头节点
}
//遍历链表输出
void printList(ListNode *head)
{
ListNode *p = head;
while(p != NULL)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int len = sizeof(arr) / sizeof(int);
ListNode *head = createList(arr, len);
printList(head);
return 0;
}
```