Member 12966147 Ответов: 1

Я хочу проверить свой код, достаточно ли он хорош, учитывая сложность времени и пространства?


//program to create a linked list
//created on 21/1/17 completed after struggling for hours....
#include<stdio.h>
#include<stdlib.h>
struct list
{
    int no;
    struct list *next;
};
int main(void)
{
    struct list *head,*p;
    int no_of_nodes;
    
    head=(struct list*)malloc(sizeof(struct list));
    p=head;
    
        printf("Type the data you want to insert: ");
             scanf("%d",&(p->no));
              p->next=(struct list*)malloc(sizeof(struct list));
              
             printf("do you want to continue if 'yes' type -- how many times you want to continue: ");
             scanf("%d",&no_of_nodes);
            while(no_of_nodes>0)
        {
            if(no_of_nodes>=1)
          {
              p=p->next;
             printf("\nType the data you want to insert: ");
             scanf("%d",&(p->no));
              p->next=(struct list*)malloc(sizeof(struct list));
      
          }
              no_of_nodes--;
             if(no_of_nodes==0)
            {
                p->next=NULL;
                break;
            }
     
            
        }
    p=head;
    printf("The nos are: \n");
     while(p!=NULL)
    {
        
        printf("%d\n",p->no);//this print the nos in the node link  by link
        p=p->next;//this points to the next node
        
    }
}


Что я уже пробовал:

я протестировал свой код, и он работает отлично, но дело в том, что я сделал это по-другому, тогда как то, что сделал мой учитель, было другим, я сделал это более подходящим на мой вкус!

NotPolitcallyCorrect

Был ли вопрос, который вы забыли задать?

1 Ответов

Рейтинг:
1

Richard MacCutchan

while(no_of_nodes>0)
{
    if(no_of_nodes>=1)
    {

То if предложение является избыточным, так как цикл не может продолжаться, если no_of_nodes меньше 1.

Кроме того, когда вы создаете узел, вы должны инициализировать его таким образом, чтобы p->next является нулевым. Только когда вы добавляете следующий узел в цепочку, вы должны установить адрес нового узла в p->next


Afzaal Ahmad Zeeshan

5ед.