如何理解单向链表的创建
How to understand the creation of a singly linked list
>问题
我在理解使用 c++ 创建单向链表的教程的代码(而不是含义)方面遇到了一些困难。
法典
typedef int ElemType;
struct Node{
ElemType data;
Node *next;
};
class LinkList{
private:
Node *Head;
public:
LinkList();
~LinkList();
void CreateList1(int n);
void CreateList2(int n);
void ListInsert(int i, int e);
int ListDelete(int i);
int GetElem(int i);
int LocateElem(int e);
int ListLength();
};
void LinkList::CreateList1(int n) {
//create a linked list by inserting the element in the head
Node *p, *s;
p = Head;
cout<<"请依次输入"<<n<<"个数据元素值"<<endl;
for (int i =1; i<n; i++){
s = new Node;
cin>>s->data;
s->next=p->next;
p->next=s; // what does it mean? I don't get it.
}
}
void LinkList::CreateList2(int n) {
//create a linked list by inserting the element in the end
Node *p, *s;
p = Head;
cout << "请依次输入" << n << "个数据元素值" << endl;
for (int i = 1; i < n; i++) {
s = new Node;
cin >> s->data;
p->next=s;
p=s; // what does it mean? I don't get it.
}
}
注意
我不明白的代码片段被注释了。任何人都可以用有启发性的文字或数字来解释代码吗?提前谢谢。
this: [ ]
是一个节点,->
用于显示节点指向的位置。
第一种情况:
-
HEAD
将指向new node
new node
将指向HEAD
之前指向的位置
p->next=s; // what does it mean? I don't get it
这意味着:
HEAD
现在应该指向new node
[HEAD]->
iteration 1:
-------------------------------
s = new Node : [S1]
s->next = p->next : [S1]->
p->next = s : [HEAD]->[S1]
iteration 2:
-------------------------------
s = new Node : [S2]
s->next = p->next : [S2]->[S1]
p->next = s : [HEAD]->[S2]->[S1]
iteration 3:
-------------------------------
s = new Node : [S3]
s->next = p->next : [S3]->[S2]
p->next = s : [HEAD]->[S3]->[S2]->[S1]
第二种情况:
-
HEAD
将指向new node
new node
变得HEAD
p=s; // what does it mean? I don't get it
这意味着:
new node
现在也变得HEAD
[HEAD]->
iteration 1:
-------------------------------
s = new Node : [S1]
p->next = s : [HEAD]->[S1]
p = s : [HEAD,S1] // S1 is the HEAD now
iteration 2:
-------------------------------
s = new Node : [S2]
p->next = s : [HEAD,S1]->[S2]
p = s : [S1]->[HEAD,S2] // S2 is the HEAD now
iteration 3:
-------------------------------
s = new Node : [S3]
p->next = s : [HEAD,S2]->[S3]
p = s : [S1]->[S2]->[HEAD,S3] // S3 is the HEAD now
p
是指向插入点的指针。
新节点插入 p
之后。
在第一种情况下,p->next=s
,我们将新节点s
挂在p
指向的节点上,但p
本身不会改变。下一个节点仍将在Head
之后插入。
在第二种情况下,p->next=s
仍然完成,但随后我们执行 p=s
,因此插入点p
移动到列表的最后一个元素 s
。下一个节点将插入列表的末尾,而不是头部。
相关文章:
- 创建链表
- 使用 _getch 创建链表并反转列表
- 创建链表,但无法按 CPP 的预期工作
- 如何使用初始值设定项列表来指导创建链表?
- 尝试连接两种不同类型的结构来创建链表
- C++ 如何创建链表的副本作为类对象
- 我是C++新手。我在此代码中遇到错误,无法使用 SwapNodes 函数C++创建链表。该函数不交换节点
- 如何在C++中创建链表列表?
- C++简体版链表,当我加载数据以创建链表并输入更多数据时,似乎存在差距
- 尝试创建链表堆栈时出现链接器错误
- 如何在链表中创建链表
- 通过在循环C++中从文件中读取文本来创建链表
- C++ - 创建链表时出现段错误
- 创建链表,模板化堆栈
- 使用基类和派生类创建链表
- 第一次尝试创建链表
- 创建链表
- 如何使用结构体创建链表
- 在c++中创建链表
- 创建链表插入函数,但代码未运行