2017-06-17 48 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 :) –