30/09/2018, 20:21

Cần giúp ở phần tạo danh sách liên kết đơn!

mọi người check họ em với ạ, em muốn tạo danh sách và hiển thị nó mà làm mãi ko đc ạ, e cảm ơn ạ.

#include <stdio.h>
#include  <conio.h>
#include <stdlib.h>
typedef struct node{
	int data;
	node *next;
}node;
typedef struct list{
	node *head;
	node *tail;
}list;

void init(list &l)
{
	l.head=l.tail=NULL;
}

node* newnode(node *p, int x)

{
	p=(node*)malloc(sizeof(node));
	p->data=x;
	p->next=NULL;
	return p;
}
void addnode(list &l, node *p)
{
	if(l.head=NULL) l.tail=p;
	else
	{
		l.tail->next=p;
		l.tail=p;
	}
}
void newlist(list &l)
{
	int n;
	printf("Nhap so phan tu:");
	scanf("%d",&n);
	init(l);
	for(int i=1; i<=n;i++)
	{
		int x,k;
		printf("Nhap gia tri: ");
		scanf("%d",&x);
		node *p=newnode(p,x);
		addnode(l,p);
	}
}
void hienthids(list l)
{
	node *p=l.head;
	for(p=l.head;p=NULL;p=p->next)
	{
		printf("%d",p->data);
	}
}
main()
{
	list list;
	newlist(list);
	hienthids(list);
	getch();
}
Hai Nguyen viết 22:28 ngày 30/09/2018
node* newnode(node *&p, int x) //
{
	p = (node*)malloc(sizeof(node));
	p->data = x;
	p->next = NULL;
	return p;
}
void addnode(list &l, node *&p) //
{
	if (l.head = NULL) l.tail = p;
	else
	{
		if (l.tail == l.head) {
			l.tail = p;
		}
		else {
			l.tail->next = p;//
		}
		
		l.tail = p;
	}
}

Bạn thử sửa lại như trên xem

Pham Van Hai viết 22:27 ngày 30/09/2018

Bạn có 2 lỗi sai trong hàm addnode

  • Thứ nhất bạn dùng phép gán (=) thay so phép so sánh bằng trong lệnh if:

  • Thứ 2 bạn không khởi tạo node nào cho head cả thì làm sao mà bạn biết đầu danh sách ở đâu.
    Bạn sửa lại như này

    if (l.head == NULL) {
    l.head = l.tail = p;
    } else {
    // code như cũ
    }

rem hoang viết 22:34 ngày 30/09/2018

oke. đã thành công. cảm ơn bạn nhiều lắm

Bài liên quan
0