2016-07-19 32 views
-1
#include <stdio.h> 
#include <stdlib.h> 

typedef struct nodeNum 
{ 
    int num; 
    struct nodeNum *next; 
} t_nodeNum; 


// Functions declaration ---------------------------- 
int menu(); // display menu and return choice 

t_nodeNum* addition(t_nodeNum *node, int n); 

void print_list(t_nodeNum *node); 
// ---------------------------------------------------- 

// Main program to test link list functions 
int main() 
{ 
    int choice; 

    t_nodeNum *pnode = NULL; 
    t_nodeNum *head = NULL; 
    t_nodeNum *temp = NULL; 

    int numAdd = 0; 
    int len = 0; 
    int first = 1; 

    do 
    { 
     choice = menu(); 

     switch (choice) 
     { 
      case 1: 
      { 
       printf("Please enter number : \n"); 
       scanf("%d", &numAdd); 
       if (first) 
       { 
        pnode = (t_nodeNum *)malloc(sizeof(t_nodeNum)); 
        if (pnode == NULL) 
        { 
         printf("\n Error in allocation\n"); 
         exit(0); 
        } 

        pnode->num = numAdd; 
        pnode->next = NULL; 
        first = 0; 
        head = pnode; 
       } 
       pnode = addition(pnode, numAdd); 
       break; 
      } 

      case 4: 
      { 
       printf("\n Print List: "); 
       print_list(head); 
       break; 
      } 
     } 
    } 
    while (choice != 5); 

    return 0; 
} 

// function menu display menu and return choice 
int menu() 
{ 
    int choice = 0; 

    do 
    { 
     printf("Please choose option to do: \n"); 
     printf("1. addition\n"); 
     printf("2. deletion\n"); 
     printf("3. search\n"); 
     printf("4. print\n"); 
     printf("5. exit\n"); 
     printf("\n option = "); 

     scanf("%d", &choice); 
    } 
    while (choice < 1 || choice > 5); 

    return choice; 
} 

// function addition to add item to linked list in recursion 
t_nodeNum* addition(t_nodeNum *p, int numAdd) 
{ 
    int len = 0; 

    if (p == NULL) 
    { 
     p = (t_nodeNum *)malloc(sizeof(t_nodeNum)); 
     if (p == NULL) 
     { 
      printf("\n Error in allocation\n"); 
      exit(0); 
     } 

     p->num = numAdd; 
     p->next = NULL; 
    } 
    else 
    { 
     p = addition(p->next, numAdd); 
    } 
    return (p); 

} 

// function print_list to print linked list in recursion 
void print_list(t_nodeNum *head) 
{  
     printf("%d ", head->num); 
     if (head->next == NULL) 
     { 
      printf("\n"); 
      return; 
     } 

     print_list(head->next); 

} 

沒有與另外功能也不能正常工作,以新的項目添加到鏈接列表,我不知道什麼是錯了,請幫 增加新的項目之後的問題,不要打印列表它僅僅顯示的第一個項目在遞歸C語言鏈接列表添加元素

+0

遞歸是錯誤的方法。如果你有10,000個節點呢?所使用的堆棧內存將非常龐大。用指針迭代列表。 –

+0

@SteveWellens這裏的所有遞歸都是尾遞歸,不是嗎? –

+0

有三種情況需要處理:'p == NULL','p-> next == NULL',和'p-> next!= NULL'。 – user3386109

回答

0

在你main功能 -

pnode = addition(pnode, numAdd); 

,而不是pnode你需要傳遞pnode->next -

pnode = addition(pnode->next, numAdd); 

第一個電話的問題是,pnode不是NULL所以它只是在頭位置添加新的元素替換以前的值並返回。

因此,新節點沒有被創建。

+0

你好,我嘗試你的建議,我主要更改爲pnode = addition(pnode-> next,numAdd);但它沒有解決問題還有其他東西仍然是越野車! – user3879626