Danh sách liên kết từ C sang C++

Mình có học theo video này về danh sách liên kết trong C.
Danh sách liên kết trong C

Sau đó mình đã chuyển code trong video sang của C++.
Mà sao code chạy đến phần nhập xong data thì không in ra được nhỉ.

Mọi người giúp mình với.
Mình cảm ơn.

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

struct SoNguyen
{
    int data;
    struct SoNguyen *Tiep;
};
typedef struct SoNguyen SONGUYEN;

void TaoDanhSach(SONGUYEN *pDau)
{
	int repeat;
    SONGUYEN *p;
    do
    {
		if(pDau==NULL)
		{
			SONGUYEN *pDau = new SONGUYEN;
			p = pDau;
		}
		else
		{
			p = pDau;
			while(p->Tiep != NULL)
			{
				p = p->Tiep;
			}
			p->Tiep = new SONGUYEN; 
			p = p->Tiep;
		}
		cout<<"\nNhap du lieu:";
		cin>>(p->data);
		cout<<"Ban muon nhap tiep khong:";
        cin>>repeat;
	}while(repeat!=0);
}

void Xuat(SONGUYEN *pDau)
{
	SONGUYEN *p = pDau;
	if(p==NULL)
	{
		return;
	}
	while(p!=NULL)
	{
		cout<<(p->data);
		p = p->Tiep;
	}
}


/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {


	SONGUYEN *pDau = NULL;
	TaoDanhSach(pDau);
	Xuat(pDau);

	return 0;
}

Ai giải đáp giúp mình với ạ :frowning:

Code của bạn không phải là cách chuyển đúng đâu bạn nhé.
Cách chuyển đúng thì phải tựa tựa như vầy nè:

#include <iostream>
#include <list>

using SoNguyen = std::list<int>;

SoNguyen TaoDanhSach(){
    int data;
    SoNguyen r;

    while (std::cin >> data && data != 0) {
        r.emplace_back(data);
	}
    
    return r;
}

void Xuat(const SoNguyen& l){
    for (auto n: l){
        std::cout << n << ' ';
    }
    std::cout << '\n';
}

void Xuat2(const SoNguyen& l){
    auto pHead = begin(l);
    while (pHead != end(l)){
        std::cout << *pHead << ' ';
        pHead = std::next(pHead);
    }
    std::cout << '\n';
}


int main() {
	auto pDau = TaoDanhSach();
	Xuat(pDau);
        Xuat2(pDau);
	return 0;
}
1 Like

Người ta đang cài đặt list mà trời ơi.

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?