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();
}
Bài liên quan
Bạn thử sửa lại như trên xem
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ũ
}
oke. đã thành công. cảm ơn bạn nhiều lắm