[英]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.
}
}
我不理解的代碼段已被注釋。 任何人都可以用有啟發性的文字或數字解釋代碼嗎? 提前致謝。
這: [ ]
是節點,並且: ->
用於顯示節點指向的位置。
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
。 下一個節點將插入到列表的末尾,而不是頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.