gpt4 book ai didi

c - 本链表程序回顾

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:03 25 4
gpt4 key购买 nike

这是链表上的一个程序,它打印给定的输入。但是是否可以在不使用 if(start==NULL) ...else .. 语句的情况下做到这一点?

#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node* next;
}* start = NULL;

void main()
{
struct node* tmp;
struct node *ptr, *tmp1;

int n = 0;
int choice = 2;

while (1)
{
printf("Enter a number less than 3 to continue");
scanf("%d", &choice);
if (choice >= 3)
break;

printf("Enter the input");
scanf("%d", &n);
// n=n+10;
if (start == NULL)
{
tmp = (struct node*)malloc(sizeof(struct node));
start = tmp;
start->data = n;
ptr = start;
}
else
{
tmp = (struct node*)malloc(sizeof(struct node));
ptr->next = tmp;
tmp->data = n;
ptr = tmp;
}
}
tmp->next = NULL;


printf("\nThe output of the linked list is\n");
n = 0;
ptr = start;
while (ptr != NULL)
{
printf("\n 1 ptr = %d", ptr->data);
ptr = ptr->next;
}
}

最佳答案

is it possible to do it Without using the if(start==NULL) ...else .. statement?

创建一个头节点并只使用它的 .next 成员。

#include <stdio.h>
#include <malloc.h>

struct node {
int data;
struct node* next;
};

int main(void) {
struct node head = {.next = NULL}; // only need .next
struct node *ptr = &head;

while (1) {
// ...

int n;
printf("Enter the input ");
fflush(stdout);
if (scanf("%d", &n) != 1) {
break;
}
ptr->next = malloc(sizeof *ptr->next);
if (ptr->next == NULL) {
break;
}
ptr = ptr->next;
ptr->data = n;
ptr->next = NULL;
}

printf("\nThe output of the linked list is\n");
ptr = head.next; // The start of the list is here
while (ptr) {
printf(" 1 ptr = %d\n", ptr->data);
ptr = ptr->next;
}
}

关于c - 本链表程序回顾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com