注册 登录
编程论坛 C语言论坛

有大佬知道为什么do while循环里重复定义结构指针是可以的呢,还有给结构指正赋NUll是怎么回事,有啥好处

铁甲 发布于 2020-11-11 09:51, 1447 次点击
#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
int value;
struct _node *next;
}Node;
int main(int argc,char const *argv[]){
Node *head=NULL;
int number;
do {
scanf("%d",&number);
if(number!=-1){
Node *p=(Node *)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
Node *last=head;
if(last){
while(last->next){
last=last->next
}
last->next=p;
}
else {
head=p;
}
}while(number!=-1);

return 0;
}
4 回复
#2
lin51616782020-11-11 09:53
先把对齐缩进处理好
代码写在[ c o d e ]这个标签里面
#3
铁甲2020-11-11 09:56

#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
    int value;
    struct _node *next;
}Node;
int main(int argc,char const *argv[]){
    Node *head=NULL;
    int number;
    do {
        scanf("%d",&number);
        if(number!=-1){
            Node *p=(Node *)malloc(sizeof(Node));
            p->value=number;
            p->next=NULL;
            Node *last=head;
            if(last){
                while(last->next){
                last=last->next;
            }
                last->next=p;
            }
            else {
                head=p;
            }
        }
    }while(number!=-1);

return 0;
}
#4
rjsp2020-11-11 10:14
程序代码:
#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
    int value;
    struct _node *next;
} Node;

int main( void )
{
    Node* head = NULL;
    for( int number; scanf("%d",&number)==1 && number!=-1; )
    {
        Node** last = &head;
        for( ; *last; last=&(*last)->next );

        (*last) = malloc( sizeof(Node) );
        (*last)->value = number;
        (*last)->next = NULL;
    }

    for( Node* p=head; p; p=p->next )
        printf( "%d ", p->value );
}
#5
lin51616782020-11-11 10:44
弄清楚一个基本概念
运行时和编译期
循环重复执行这个说的是运行时发生的事情
声明/定义变量这个是编译期的事情
定义变量的时候不用考虑有没有循环
变量会不会重复定义 只和作用域这个概念有关系
同一个作用域里面 多次定义是错的
你的代码里面 last 这个变量所在的作用域只定义一次 语法上完全没问题
1