如何创建用于存储字符串的通用链表? [英] How can I create a generic linked list for storing strings?

查看:282
本文介绍了如何创建用于存储字符串的通用链表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用void *创建一个链表,以在每个节点中存储一个单词。我不确定在哪个位置对数据进行类型转换,我仍然会收到错误:



linked_list_generic.c:63:10:错误:格式'%s '期望类型为'char *'的参数,但参数2的类型为'void *'[-Werror = format =]

printf(%s,temp-> data);



我是通用链接列表的新手,所以任何帮助都会很棒。



我有什么试过:



I am trying to create a linked list using a void* to store a word in each node. I am not sure at which point to typecast the data, and i continue to get the error:

linked_list_generic.c:63:10: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘void *’ [-Werror=format=]
printf("%s ", temp->data);

I am new to generic linked lists so any help would be great.

What I have tried:

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

/*Typedef declarations*/

typedef struct Node
{
	void* data;
	struct Node* next;
}Node;

typedef struct 
{
	Node* head;
}Linked_List;

/*------------------------------------------------------------------*/

Linked_List* create_empty_list(void)
{
	Linked_List* new_head; 
	new_head = (Linked_List*)malloc(sizeof(Linked_List)); 
	new_head->head = NULL;
	
	return new_head;
}

/*------------------------------------------------------------------*/
	
Node* insert_end(Linked_List* list, void* data)
{
	Node* new_node;
	Node* temp;
	new_node = (Node*)malloc(sizeof(Node));
	new_node->data = malloc(sizeof(char*));
	new_node->data = (char*)data;
	new_node->next = NULL;
	if(list->head == NULL)
	{
		list->head = new_node;
	}
	else
	{
		temp = list->head;
		while(temp->next != NULL)
		{
			temp = temp->next;
		}
		
		temp->next = new_node;
	}
	return(list->head);
}
	
/*------------------------------------------------------------------*/	

void display(Linked_List* list)
{
	Node* temp;
	temp = list->head;
	while(temp != NULL)
	{
		printf("%s ", temp->data);
		temp = temp->next;
	}
}

/*------------------------------------------------------------------*/
		
void free_list(Linked_List* list)
{
	while(list->head != NULL)
	{
		Node* temp = list->head;
		list->head = temp->next;
		free(temp);
	}
}

/*------------------------------------------------------------------*/
/*Main code to test linked list*/	
	
int main(void)
{
	
	/*int num_elements, i;*/
	char str[20];
	
	Linked_List* char_list = create_empty_list();
	
	printf("Enter a word\n");
	scanf("%s", str);
	
	char_list->head = insert_end(char_list, str);
	
	
	printf("The list is: ");
	display(char_list);
	printf("\n\n");
	
	
	free_list(char_list);
	
	return(0);
	
}

推荐答案

尝试:

Try:
printf("%s ", (char*)(temp->data));


这篇关于如何创建用于存储字符串的通用链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆