c语言代码修改的问题 如图所示 //1 //2 //3 //4 //5 //6 //7
怎么去修改
if(head == NULL)
{
printf("X");
return;
}
printf("%d",head->data);
while(head->next != NULL)
{
head= head->next ;
printf("-> %d",head->data);
}
printf("-> X");
那能用啥输出啊?printf可以么?
void print(struct node *head) {
while(head !=NULL)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node
{
struct node *next;
int data;
};
void print(struct node *head);
struct node *strings_to_list(int len, char *strings[]);
void destroy(struct node *head);
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("%s num1 [[num2] ...]", argv[0]);
return 1;
}
struct node *head = strings_to_list(argc - 1, &argv[1]);
print(head);
destroy(head);
return 0;
}
void print(struct node *head)
{
while (head)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
struct node *strings_to_list(int len, char *strings[])
{
struct node *head = NULL;
for (int i = len - 1; i >= 0; i--)
{
struct node *n = malloc(sizeof(struct node));
assert(n != NULL);
n->next = head;
n->data = atoi(strings[i]);
head = n;
}
return head;
}
void destroy(struct node *head)
{
while (head)
{
struct node *p = head;
head = head->next;
free(p);
}
}
你怎么申请堆空间不知道释放呢,free呢
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node {
struct node *next;
int data;
};
void print(struct node *head);
struct node *strings_to_list(int len, char *strings[]);
//void destroy(struct node *head);
int main(int argc, char *argv[]) {
if (argc < 2)
{
printf("%s num1 [[num2] ...]", argv[0]);
return 1;
}
struct node *head = strings_to_list(argc - 1, &argv[1]);
print(head);
return 0;
}
void print(struct node *head) {
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
}
struct node *strings_to_list(int len, char *strings[]) {
struct node *head = NULL;
for (int i = len - 1; i >= 0; i = i - 1) {
struct node *n = malloc(sizeof (struct node));
assert(n != NULL);
n->next = head;
n->data = atoi(strings[i]);
head = n;
}
return head;
}