如何理解单向链表的创建

How to understand the creation of a singly linked list

本文关键字:创建 链表 何理解      更新时间:2023-10-16

>问题

我在理解使用 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 。下一个节点将插入列表的末尾,而不是头部。