链接: https://blog.csdn.net/qq_41620518/article/details/81143414.
看了好多关于链表的讲解,感觉上面这个是最简单易懂的,所以将代码粘了过来,同时加了链表展示的函数,不懂的细节可以点上面的链接
#include <iostream>
using namespace std;
// 创建一个单链表结构体
struct ListNode{
int m_key;
ListNode* next;
};
// 创建一个单链表
void createList(ListNode* pHead){
ListNode* p = pHead;
for (int i = 1; i < 10; ++i) {
ListNode* pNewNode = new ListNode;
pNewNode->m_key = i; // 将新节点的值赋值为i
pNewNode->next = NULL;
p->next = pNewNode; // 上一个节点指向这个新建立的节点
p = pNewNode; // p节点指向这个新的节点
}
}
// 展示之前创建的单链表
void Display(ListNode* head) {
ListNode *p = head;
cout<<"Display the list from Head to Tail:"<<endl;
while(p!=0){
cout << p->m_key <<" ";
p=p->next;
}
cout << endl;
}
// 主函数
int main(){
ListNode* head = NULL;
head = new ListNode;
head->m_key = 0;
head->next = NULL;
createList(head);
Display(head);
return 0;
}