考虑到时间复杂度和空间复杂性,我想回顾一下我的代码是否足够好? [英] I want to review my code whether it is good enough considering the time compleixity and space complexity?
本文介绍了考虑到时间复杂度和空间复杂性,我想回顾一下我的代码是否足够好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//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
}
}
我尝试过的事情:
我已经测试了我的代码,并且代码运行得很好,但问题是我做的方式有所不同,而老师所做的却与我有所不同,我的代码更适合我的口味!
What I have tried:
i have tested my code and it runs perfectly well but the thing is I did it differently whereas what my teacher did was different I have done it more suitable to my taste!
推荐答案
while(no_of_nodes>0)
{
if(no_of_nodes>=1)
{
if
子句是多余的,因为如果no_of_nodes
小于1,则循环将无法继续.
另外,创建节点时,应将其初始化,以使p->next
为NULL.仅当在链中添加下一个节点时,才应将新节点的地址设置为p->next
The if
clause is redundant as the loop cannot continue if no_of_nodes
is less than 1.
Also, when you create a node you should initialise it such that p->next
is NULL. Only when you add the next node in the chain should you set the address of the new one into p->next
这篇关于考虑到时间复杂度和空间复杂性,我想回顾一下我的代码是否足够好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文