创建链表的过程详解
本人是一名刚开始学习算法的小白,今天遇到了一些关于链表的创建问题,查了一些资料,我把它们整理了一下,希望大家多多指教。
整体的代码:
#include<iostream>
using namespace std;
struct Node {
int val;
Node* next;
};
#创建
Node* creatlist(int n) {
Node* Head=new Node; //头节点 不存储数据
Head->next = NULL;
Node* pre = Head; //指向下一个节点的过渡值
cout << "请依次输入" << n << "个链表的值:";
for (int i = 0;i < n;i++) {
Node* temp = new Node;
cin >> temp->val;
pre->next = temp;
pre = temp;
temp->next = NULL;
}
return Head;
}
#显示
void display(Node* head) {
Node* temp=head->next;
int e;
cout << "该链表的遍历依次为:";
while (temp!=NULL) {
e = temp->val;
cout << e << " ";
temp = temp->next;
}
cout << "\n";
}
int main() {
int nums;
cout << "请输入链表的长度:";
cin >> nums;
Node* head = creatlist(nums);
display(head);
return 0;
}
解释
1、基本概念:
链表是物体存储单元上不连续的储存结构,数据元素是由链表上的指针所连接。
每个节点都包含两部分:存储数据的数据域,和存储下一个节点的地址的指针域。

根据上图,利用数据结构struct建立一个节点:
struct Node {
int val;<

本文详细介绍了如何在C++中创建链表,包括链表的基本概念、节点结构、创建链表的过程(创建头节点、输入节点值并连接)、显示链表的方法,以及解决链表相关问题的实例,如合并、删除元素和判断链表相交。
最低0.47元/天 解锁文章
6796





