我的反向链接列表代码可以进一步增强吗

标签 c pointers data-structures linked-list

这是我的程序,它创建一个链接列表并反转它。

#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 tree\n");
    scanf("%d", &i);
    create_list(i);
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);
    while (choice!=0){
     printf("Enter a no for link list\n");
        scanf("%d",&i);
//  printf("going to create list in while\n");
    create_list(i);
        travel_list(); 
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);
    }
    printf("reversing list\n");
     reverse_list();
     travel_list();
 }


// end of function main
void create_list (int data)
{
 struct node *t1,*t2;
 //printf("in function create_list\n");
 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=%d\n",temp->data);
//  printf("the adress of node created %p\n",temp);
    return temp;
}
void travel_list(void )
{
 struct node *t1;
 t1=list;
 printf("in travel list\n");
 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;
}

以上是完整的工作代码。 我想知道上面的代码是否可以进一步增强?

最佳答案

  • 使缩进和空格的使用保持一致
  • 使用有意义的标识符而不是 t1t2t3
  • 使 data 成员成为通用类型,例如 void * 而不是 int
  • 不要使用全局变量,将struct node * 指针传递给您的函数。

关于我的反向链接列表代码可以进一步增强吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6411516/

相关文章:

arrays - char *name[10] 和 char (*name)[10] 有什么区别?

c - 将数据存储到一个充满指针的结构中

c - 将字符传递给 char *

c++ - 数据结构是否适合放置 shared_ptr?

c++ - printf 导致崩溃

c - 为什么 main() 不需要返回类型(比如 int),即使它返回一个整数?

c++ - uint128_t 没有命名类型

c - 获取空长度

c# - 关系的数据结构

java - 想要从第一个到最后一个元素。但最后回到第一