2013-03-11 80 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設置列表頭。 (後者通常是可取的,因爲全局變量常常等待發生。)