这是我的程序,它创建了一个链接列表并对其进行反转
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *list=NULL;
struct node *root=NULL;
static int count=0;
struct node *create_node(int);//function to create node
void travel_list(void);
void create_list(int);
void reverse_list(void);
int main()
{
int i, j, choice;
printf("Enter a number this will be root of treen");
scanf("%d", &i);
create_list(i);
printf("Enter 1 to enter more numbers n 0 to quitn");
scanf("%d", &choice);
while (choice!=0){
printf("Enter a no for link listn");
scanf("%d",&i);
// printf("going to create list in whilen");
create_list(i);
travel_list();
printf("Enter 1 to enter more numbers n 0 to quitn");
scanf("%d", &choice);
}
printf("reversing listn");
reverse_list();
travel_list();
}
// end of function main
void create_list (int data)
{
struct node *t1,*t2;
//printf("in function create_listn");
t1=create_node(data);
t2=list;
if( count!=0)
{
while(t2->next!=NULL)
{
t2=t2->next;
}
t2->next=t1;
count++;
}
else
{
root=t1;
list=t1;
count++;
}
}
struct node *create_node(int data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->next=NULL;
// printf("create node temp->data=%dn",temp->data);
// printf("the adress of node created %pn",temp);
return temp;
}
void travel_list(void )
{
struct node *t1;
t1=list;
printf("in travel listn");
while(t1!=NULL)
{
printf("%d-->",t1->data);
t1=t1->next;
}
printf("n");
}
void reverse_list(void)
{
struct node *t1,*t2,*t3;
t1=list;
t2=list->next;
t3=list->next->next;
int reverse=0;
if(reverse==0)
{
t1->next=NULL;
t2->next=t1;
t1=t2;
t2=t3;
t3=t3->next;
reverse++;
}
while(t3!=NULL)
{
t2->next=t1;
t1=t2;
t2=t3;
list=t1;
travel_list();
t3=t3->next;
}
t2->next=t1;
list=t2;
}
以上是一个完整的工作代码。我想知道是否可以对上述代码进行进一步的增强?
- 使缩进和空白的使用保持一致
- 使用有意义的标识符,而不是
t1
、t2
和t3
- 使
data
成员成为泛型类型,例如void *
而不是int
- 不要使用全局变量,将
struct node *
指针传递给函数