Lỗi danh sách liên kết đơn c++

<#include<iostream>
using namespace std;

struct tree{
	int item;
	struct tree *next;
};
		tree *creat_tree(int );
		void insert_top(tree *,int);
		void show(tree *);
tree *creat_tree(int x){
	tree *p;
	p=new tree;
	p->item=x;
	p->next=NULL;
	return p;
}
void insert_top(tree *p,int x){
	tree *q;
	q=creat_tree(x);
	q->next=p;
	p=q;
	return;
}
void insert_bottom(tree *p,int x){
	tree *q,*r;
	q=creat_tree(x);
	r=p;
	while(r->next!=NULL){
		r=r->next;
	}
	r->next=q;
}
void show(tree *p){
	tree *q;
	q=new tree;
	q=p;
	while(q->next!=NULL){
	cout<<q->item;
	q=q->next;
	}
}
main(){
	tree *p;
	p=creat_tree(0);
	insert_top(p,1);
	insert_top(p,2);
	insert_bottom(p,3);
	show(p);
}
/>

lỗi là khi chèn thêm phần tử vào danh sách nhưng nó không xuất ra màn hình

1 Like

Mình code bằng C, bạn tham khảo thử.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

typedef struct pNode
{
	int info;
	struct pNode* pNext;
}Node;

typedef struct list
{
	Node* pHead;
	Node* pTail;
}List;

void KhoiTaoDanhSach(List &l)
{
	l.pHead = NULL;
	l.pTail = NULL;
}

Node* GetNode(int x)
{
	Node* p;
	p = new Node;
	if (p==NULL)
	{
		printf("Khong tao duoc node");
		exit(1);
	}
	p->info = x;
	p->pNext = NULL;
	return p;
}
 
void Them(List &l, int x)
{
	Node* p = GetNode(x);
	//Them cuoi danh sach
	if (l.pHead==NULL)//danh sach rong
	{
		l.pHead = p;
		l.pTail = p;
	}
	else //danh sach co it nhat 1 phan tu
	{
		l.pTail->pNext = p;
		l.pTail = p;
	}
}

void XemDanhSach(List l)
{
	Node* p = l.pHead;
	while (p!=NULL)
	{
		printf("%d ", p->info);
		p=p->pNext;
	}
}

int main()
{ 
	List l;
	KhoiTaoDanhSach(l);
	Them(l, 10);
	Them(l, 20);
	Them(l, 30);
	XemDanhSach(l);
	return 0;
} 

mình đang dùng danh sách liên kết còn code của bạn dùng hàng đợi rồi

while(p!=NULL) - hàm show nhé

không biết bạn có insert được không, nhưng mình nhớ là cái này không được. Cái p ở trong hàm insert_top khác vs p ở hàm main

  • Hàm insert_top gán p=q thì p sẽ thay đổi nhưng ra khỏi hàm sẽ giữ nguyên. Sửa lại thành insert_top(tree * &p,int x)
  • Hàm show: q=new tree la không cần. Việc q->next==NULL vẫn có item nên sửa lại while(q->next!=NULL) thành while(q!=NULL)
    Code sửa lại : http://ideone.com/y5GIhJ
1 Like

tại sao hàm insert_bottom không có cái (tree *&p,int x) ?

Cả (tree *&p,int x)insert_bottom(tree *p,int x) đều dc. Vì p cũng không thay đổi :smile:

1 Like

A post was merged into an existing topic: Topic lưu trữ các post off-topic - version 3

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