2013-03-11 77 views
0

我正在尝试创建一个程序来创建和显示链接列表。链接列表功能

现在我遇到了我的create_list()函数的问题,它没有创建任何列表。

我做错了什么?

对不起,我英文不好:/

CODE:

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node { 
    int data; 
    struct node *next; 
} node; 

int main(){ 

    node *start; 
    start = NULL; 
    int a,n,on = 1; 

    while(on == 1){ 
     printf(" \n choose: \n 1 --- create list \n 2 --- display list \n"); 
     scanf("%d",&n); 
     switch(n){ 
      case 1: 
       printf("-------------------------------------------- \n"); 
       printf(" Enter the elements. The last element is 0 \n"); 
       printf("-------------------------------------------- \n"); 

       Create_list(); 
       Display_list(start); 
       break; 

      case 2: 
       Display_list(start); 
       break; 
     } 
    } 

    system("pause"); 
    return 0; 
} 

void Display_list(node *curr){ 
    if(curr){ 
     while (curr->next != NULL){ 
        printf("%d \n",curr->data); 
        curr=curr->next; 
     } 
    } else { 
     printf(" \n The list is not created ! \n"); 
    } 
} 

void Create_list(node *curr){ 

    int i; 
    node *start = NULL; 



    if (start == NULL){ 
     curr = (node *)malloc(sizeof(node)); 
     start=curr; 

     while (i != 0){ 
      scanf("%d",&i); 
      if(i == 0){ 
       curr->next=NULL; 
       curr=start; 
      } else { 
       curr->data=i; 
       curr->next=(node *)malloc(sizeof(node)); 
       curr=curr->next; 
      } 
     } 

    } else { 
      printf(" \n list already exists ! \n"); 
    } 
}      
+0

你的压痕伤害了我的眼睛! – 2013-03-11 13:45:12

回答

1

函数Create_List(node * curr)需要一些参数。你没有从main()传入任何参数。你的代码编译了吗?

函数Create_List(node * curr)需要一些参数。你没有从main()传入任何参数。你的代码编译了吗?

你应该做的是取一个主节点,它将存储链表的第一个节点的位置。

void Insert(struct node **q, int num) //Num is the data to be added and **q is the pointer to the first node of the list. 
{ 
struct node *temp, *r; 
temp = *q; 
if (*q == NULL) { 
    temp = ((struct node *)malloc(sizeof(struct node))); 
    temp->data = num; 
    temp->link = NULL; 
    *q = temp; 
} 
else { 
    while (temp->link != NULL) 
     temp = temp->link; 

    r = ((struct node *)malloc(sizeof(struct node))); 
    r->data = num; 
    r->link = NULL; 
    temp->link = r; 
} 
} 
+0

是的,当我输入1,2,3,0时打赌。它显示我“该列表未创建!”。 – 2013-03-11 13:45:48

+0

“通过&开始(作为节点**)从主进入Create_list并修改*开始设置列表头。”正如cHao所说。 – SureshS 2013-03-11 13:55:06

0

Create_liststartmain相关start。由于两者都是各自职能的本地人,所以甚至不能看到其他人。所以如果你愿意,设置start实际上并没有设置start。 :P

你需要无论是从main带来start之外的功能,并使其全球性的,或通过&start(为node**)为Create_list和修改*start设置列表头。 (后者通常是可取的,因为全局变量常常等待发生。)