2017-06-17 52 views
-1

我試圖用c語言遞歸創建線性鏈表, 但是從這裏繼續粘住,並且代碼不能處理錯誤「Linker Tools Error LNK2019」。可悲的是我不明白髮生了什麼事。這是我的代碼。用C語言創建並顯示線性鏈表(遞歸地)

感謝您提前給予的大力幫助。

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


struct node 
{ 
    char num;      //Data of the node 
    struct node *nextptr;   //Address of the next node 
}; 
typedef struct node element; 
typedef element *link; 
link head; 


void displayList();   // function to display the list 

int main() 
{ 
    char s[] = "abc"; 
    link stol(s); 
    { 
     link head; 
     if (s[0] == '\0')return(NULL); 
     else { 
      head = (link)malloc(sizeof(element)); 
      head->num = s[0]; 
      head->nextptr = stol(s + 1); 
      return(head); 
     } 
    } 

    printf("\n\n Linked List : To create and display Singly Linked List :\n"); 
    printf("-------------------------------------------------------------\n"); 

    displayList(); 
    return 0; 
} 


void displayList() 
{ 
    link tmp; 
    if (head == NULL) 
    { 
     printf(" List is empty."); 
    } 
    else 
    { 
     tmp = head; 
     while (tmp != NULL) 
     { 
      printf(" Data = %d\n", tmp->num);  // prints the data of current node 
      tmp = tmp->nextptr;      // advances the position of current node 
     } 
    } 
} 
+0

在'main'函數外(和之前)定義'stol'函數。 – BLUEPIXY

+0

謝謝。你的意思是我需要把「鏈接stol」外(和之前)的主要功能? –

+0

我的意思是喜歡[this](http://ideone.com/IHPo0I) – BLUEPIXY

回答

0

你在你的main()功能重新定義稱爲head一個link對象。它隱藏了全局變量head

刪除main中的定義可以解決您的問題,但是您應該考慮在任何情況下都將link*作爲參數傳遞給您的displayList函數。

我剛剛注意到這個說法return(head);main()。結果,你的程序也過早退出。

每當我看着你的應用程序,我發現更多的問題。如果我是你,我首先創建一個將節點添加到列表中的函數。將新節點添加到列表的前面會更容易,所以您應該先嚐試一下。嘗試添加到尾巴,一旦你得到這個運行。添加到尾部是非常相似的,但你必須'走the list first to get to the last element, exactly as you already do in displayList()`另一種方法是保持你添加到列表中的最後一個節點*的地址。就像我說的那樣,它增加了一些複雜性,所以首先要使用addToHead。

void addToHead(link* l, node* n) 
{ 
    n->nextptr = l->nextptr; 
    l->nextptr = n; 
} 

在你的主,你可以一次分配一個新的節點,因爲你已經做的malloc()。使用整數初始化其內容num,並讓addToHead處理指針的內容。你對指針的使用是很糟糕的,但是列表很容易,addToList幾乎顯示了什麼可以和什麼應該放在指針中 - 也就是其他指針。

您可以刪除第一個printf之前在主幾乎一切()。你必須

  1. 開始循環:
  2. 寫一個提示,以便用戶知道什麼用printf()
  3. 使用的scanf( 「%d」,& N)讀取用戶輸入的事,或同等學歷。
  4. 如果用戶輸入負值,則會從循環中斷開。
  5. 的malloc()的新節點
  6. 設置其數據num = n
  7. 呼叫addToHead添加的節點。
  8. 循環直到用戶輸入空字符串或-1。

這應該採取的代碼約8至10行。如果有疑問,您可以通過谷歌或http://en.cppreference.com/w/c輕鬆找到有關scanf的文檔。

+0

謝謝!這個評論的最後我終於安排了我的整個混亂的概念性思維的'全局和局部變量'googling :) –