帮助理解C ++中的链表 [英] Help needed to understand linked list in C++

查看:95
本文介绍了帮助理解C ++中的链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中有一段链表代码。我想了解它。我完全理解它。但是,有些部分我没有得到。请解释一下H-> Data在此代码中的作用以及p-> Next在此代码中的作用。另外* H和* p在这方面做了什么。据我所知,指针保存其他变量的内存地址。



我尝试过:



I have a piece of code of linked list in c++.I want to understand it. I do understand the most of it. But, some parts I do not get. Please explain me that what H->Data does in this code and what p->Next does in this code. Also what does *H and *p do in this. For what i know that pointers hold memory address of other variables.

What I have tried:

#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;

struct List
{	int Data;
	List* Next;
};

int main()
{
    List *H, *p;
    srand(time(0));
    cout << "Initial data: ";
    H = new List; p = H;
    H->Data = rand() % 99 + 1;
    cout << H->Data << " ";
    for (int i=0; i<19; i++)
    {
        p->Next = new List;
        p = p->Next;
        p->Data = rand() % 99 + 1;
        cout << p->Data << " ";
    }
    p->Next = NULL;
    
    cout << "\nData of the list: ";
    p = H;
    while (p != NULL)
    {
        cout << p->Data << " ";
        p = p->Next;
    }

    cout << endl;
    system("pause");
    return 0;
}

推荐答案

链接列表就是名称所暗示的:通过指针链接在一起的对象列表。在这种情况下,对象是一个整数Data,指向列表中下一个项目的指针是Next。变量H是指向列表头部的指针。变量p是指向列表中项目的指针。在for循环中,它指向最后添加的项目。在while循环中,它指向迭代中的当前项。通过创建新对象并将列表中最后一项的Next指针指定给此新对象,将项添加到列表中。在while循环中,您可以看到列表是如何通过Next指针链接在一起的。指针p逐步遍历列表,一次一个项目,直到遇到一个空的Next指针,指示列表中的最后一项。



你可能想要更详细地阅读链接列表:链接列表 - 维基百科 [ ^ ]
A linked list is what the name implies : a list of objects that are linked together by pointers. In this case, the object is an integer, Data, and the pointer to the next item in the list is Next. The variable H is a pointer to the head of the list. The variable p is a pointer to an item in the list. In the for loop it points to the last item added. In the while loop it points to the current item in the iteration. Items are added to the list by creating a new object and assigning the Next pointer of the last item in the list to this new object. In the while loop you can see how list is chained together through the Next pointer. The pointer p steps through the list, one item at a time, until it encounters a null Next pointer which indicates the last item in the list.

You might want to read up on linked lists in a little more detail : Linked list - Wikipedia[^]


这篇关于帮助理解C ++中的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆