繁体   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