我在理解使用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.
}
}
我不明白的代码片段已被评论。任何人都可以用有启发性的文字或数字解释代码?提前谢谢。
答案 0 :(得分:1)
这:[ ]
是一个节点,->
用于显示节点指向的位置。
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
答案 1 :(得分:0)
p
是指向插入点的指针。
新节点在p
之后插入。
在第一种情况下,p->next=s
,我们将新节点s
挂起p
指向的节点,但p
本身不会更改。仍然会在Head
之后插入下一个节点。
在第二种情况下,p->next=s
仍然完成,但我们执行了p=s
,因此插入点p
移动到列表的最后一个元素s
。下一个节点将插入列表的末尾,而不是头部。