2011-02-07 37 views
-1

我需要採取以下代碼,並將其修改爲接受字符串作爲參數,而不是整數。最後,我需要程序獲取所有命令行參數,並將它們添加到字符串的鏈接列表中。C - 字符串鏈接列表

所以如果輸入是六七八,當我打印鏈表時,它會打印:八七六。

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

typedef struct iNode 
{ 
    int myInt; 
    struct iNode* next; 
} IntNode, *IntNodePtr; 

IntNodePtr insert(int i, IntNodePtr p) 
{ 
    IntNodePtr newp = malloc(sizeof(struct iNode)); 
    newp->myInt = i; 
    newp->next = p; 
    return newp; 
} 

printlist(IntNodePtr p) 
{ 
    if(p == NULL) 
     printf("\n"); 
    else 
    { 
     printf("%d ", p->myInt); 
     printlist(p->next); 
    } 
} 

main(int argc, char* argv[]) 
{ 
    int n = 5; 

    if(argc > 1) 
    n = atoi(argv[1]); 

    IntNodePtr iNodeList; 
    iNodeList = NULL; 
    int i = 0; 

    while(i < n) 
    { 
     iNodeList = insert(i++, iNodeList); 
     printf("List is now: "); 
     printlist(iNodeList); 
    } 
} 
+0

那麼究竟是什麼問題呢? – 2011-02-07 01:46:59

+1

閱讀[SO常見問題解答](http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions)。 – outis 2011-02-07 01:58:36

回答

0

如果打印向後解決的問題,只是保持一個全球頭PTR指向在第一個inode。當你必須打印時,(headPtr.next!= null){printf(...); }

0

我認爲你的問題與列表中項目的順序有關。

想象一下,使用鏈接列表,可以將項目添加到頭部,尾部或將其插入任意位置。

看看insert()函數,它會在哪裏添加新項?

簡單地說,您可以逆轉插入項目的順序。在現實生活中,這可能不會太好。

也許保持一個尾巴指針? 並寫一個addItemToTail()函數?