簡體   English   中英

如何理解單鏈列表的創建

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM