2013-11-15 16 views
0

我必須寫程序存儲由用戶到鏈表輸入的字符串,然後打印出它是反向 - f.e如果用戶輸入你好。輸出應該是.olleH。讀字符串鏈表

我不太拿到名單的整體思路,但是我想出了一些東西,會很感激的任何反饋。

typedef struct L { 
char c; 
struct L *next; 
}List; 

List *getInput(void) { 
    List *t = calloc(1, sizeof(List)); 
    int i; 
    for (i=0; getchar() != '.'; i++) { 
     t->c = getchar(); 
     t->next = NULL; 
     printf("%c", t->c); 
     t = t->c; 
     t->next = t->next->next; 
    } 
    return t; 
} 

int main (void) { 
    getInput(); 
    return 0; 
} 

現在我只是嘗試使用getchar()逐個字符地將它存儲在列表t中。然後我想用另一個打印它來循環向後計數。由於某些原因,它不工作,雖然和我(不完全理解名單的概念)無法找出原因。

欣賞任何幫助傢伙!

+2

爲什麼C#的標籤? –

+1

同意,對於這些標籤抱歉。這確實是C++ – user2997781

+2

@ Manu343726「printf」,「NULL」和「calloc」都存在於C++中,無論你是否喜歡它們。 (不,我認爲這應該被標記爲C++,但它不是鑄造calloc'的'返回值_is_近有效的C++分開。) –

回答

1

當你想打印輸入的字符串反向最簡單的方法在鏈表存儲串以相反的順序,即在前面加上字符因爲他們正在閱讀到列表的開頭(「頭」)。所以在開始的列表中將是空的,然後它將包含「H」,然後是「eH」,「leH」等等。下面是samblo代碼:

List *getInput(void) 
{ 
    List *l = NULL; // list head, we'll prepend nodes here 
    int c;   // variable for current read character 

    while ((c = getchar()) != EOF) {  // read characters one by ine, until end-of-file 
     List *n = calloc(1, sizeof(List)); // create new list node 
     n->c = c;  // store read character in that node 
     n->next = l; // prepend newly created node to our list 
     l = n;  // store newly created node as head of list 
    } 

    return l; 
} 

這裏是你如何能打印清單:

void printList (List *l) 
{ 
    while (l != NULL) { // while we have not reached end of list 
     putchar(l->c); // print character stored in list 
     l = l->next; // and advance to next list node 
    } 
}