Gặp vấn đề khi vừa thêm phần tử vừa sắp xếp trên linked list

Anh ơi nay em gặp 1 vấn đề khi thao tác trên linked list. Cụ thể em muốn vừa add phần tử vừa sắp xếp luôn:

#include<stdio.h>
#include<stdint.h>

typedef struct t_node
{
	int data;
	struct t_node *next;
}node_t;
typedef node_t* p_node;
typedef struct t_collection
{
	node_t arr[20];
	p_node head;
}collection_t;
typedef collection_t* p_collection;
void AddToCollection(p_collection c, int data, int size);
void AddToCollection(p_collection c, int data, int size)
{
	int exit = 0;
	p_node n = &c->arr[size];
	n->data = data;
	p_node current = c->head;
	p_node prev = c->head;
	if(current == NULL)
	{
		n->next = c->head;
		c->head = n;
	}
	else
	{
		if(n->data >= current->data)
		{
			c->head->next = n;
			current = current->next;
			n->next = current;
		}
		else
		{
			n->next = c->head;
			c->head = n;
			exit = 1;	
		}
		while(current != NULL && exit == 0)
		{
			if(data > current->data)
			{
				prev = prev->next;
				current = current->next;
			}
			else
			{
				n->next = current;
				prev->next = n;
				exit = 1;	
			}		
		}
	}
}


int main()
{
	collection_t h;
	h.head = NULL;
	AddToCollection(&h, 2, 0);
	AddToCollection(&h, 100, 1);
	AddToCollection(&h, 11, 2);
	AddToCollection(&h, 120, 3);
	printf("%d\n",h.head->data);
	printf("%d\n",h.head->next->data);
	printf("%d\n",h.head->next->next->data);
	printf("%d\n",h.head->next->next->next->data);
	if(h.head->next->next->next->next == NULL)
	printf("FALSE");
	else printf("TRUE");		
}

Mà kết quả lại ra


Em đang thắc mắc không biết tại sao 3 kết quả cuối của mảng lại bằng nhau và tại sao phần tử next ở cuối lại không phải là NULL ạ. Mà nó vẫn thoát được vòng lặp while ạ?

Nếu bạn đã dùng kiểu lưu trữ có chỉ số:

typedef struct t_collection
{
	node_t arr[20];
	p_node head;
}collection_t;

thì bạn dùng mảng luôn cho rồi, sao phải bày vẽ ra linked_list ở đây làm gì nữa?

4 Likes

Như @nguyenchiemminhvu đề cập, cậu cài đặt linked list sai rồi :smile:
Cậu không cần collection làm gì, chỉ cần struct node để cài đặt linked list thôi.
Cài đặt lại nha cậu! :smile:

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