【发布时间】:2017-04-07 12:48:35
【问题描述】:
我在链表上有这个练习。
我已成功管理create_list() 和print_number() 功能,但我似乎无法管理listnode_t *int_to_list(int num)。
请注意,该练习基于代码模板,因此您看到的任何内容(main 和带有参数的额外函数)都带有前缀。
我们只需要在函数内部填写代码,这样代码就可以顺利编译运行。
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int digit;
struct node *next;
} listnode_t;
listnode_t *create_list(int numdigits);
void print_number(listnode_t *head);
listnode_t *int_to_list(int num);
void freelist(listnode_t * head) {
listnode_t * currentNode = head;
listnode_t * node_to_free = NULL;
while(currentNode->next != NULL) {
node_to_free = currentNode;
currentNode = currentNode->next;
free(node_to_free);
}
}
int main(int argc, char** argv)
{
listnode_t *number1, *number2, *result;
printf("Insert a number\n");
number1 = create_list(3);
printf("Insert another number\n");
number2 = create_list(5);
printf("First number: ");
print_number(number1);
printf("\n");
printf("Second number: ");
print_number(number2);
printf("\n");
// convert int to list
number1 = int_to_list(1024);
print_number(number1);
printf("\n");
freelist(number1);
freelist(number2);
return 0;
}
listnode_t * create_list(int numdigits)
{
int number[numdigits];
int i;
for(i=0; i < numdigits; i++) {
printf("Dose to %d stoixeio tou akeraiou: ", i + 1);
scanf("%d", &number[i]);
}
listnode_t * head = (listnode_t *)malloc(sizeof(listnode_t));
if(head == NULL) {
return NULL;
}
head->digit = number[numdigits - 1];
head->next = NULL;
listnode_t * currentNode = head;
for(i = numdigits - 2; i >= 0; i--) {
listnode_t * node = (listnode_t *)malloc(sizeof(listnode_t));
node->digit = number[i];
node->next = NULL;
currentNode->next = node;
currentNode = node;
}
return head;
}
void print_number(listnode_t * head)
{
listnode_t * currentNode = head;
while(currentNode != NULL) {
printf("%d", currentNode->digit);
currentNode = currentNode->next;
}
}
/* The function takes an integer and converts it to a list.
The functio returns a pointer to the first node of the list.*/
listnode_t *int_to_list(int num)
{
int newnum;
listnode_t * head = malloc(sizeof(listnode_t));
listnode_t * current = head;
current->next = malloc(sizeof(listnode_t));
while (current->next != NULL) {
current = current->next;
}
newnum = num % 10;
head->digit=newnum;
head->next=current;
num = num / 10;
while (num > 1 && num < 9) {
current->digit=newnum;
current->next=NULL;
}
newnum = num % 10;
return head;
}
感谢所有帮助。
【问题讨论】:
-
你已经有了一个从数字序列创建列表的函数 (
create_list)。您没有创建该功能吗?如果您没有创建create_list函数,也许您可以查看它以获取有关如何创建列表的灵感? -
1)
current未在int_to_list中声明 -
2) 原型
listnode_t *int_to_list(int num)添加;到最后。 -
3)
freelist不会释放最后一个节点。` -
对不起我的错..代码没有正确执行。我正在纠正它
标签: c struct linked-list