2016-12-02 33 views
-2

我知道這個問題,但我的問題不同於僅反向打印。LinkedList C++中的反向打印

void printReverse(ListNode* p){ 
    if(!p) 
     return; 
    printReverse(p->next); 
    cout << (p->val) << "->"; 
    return; 
} 

給定輸出是

3->2->1->3->2->3-> 

我要的是

3->2->1-> 
3->2-> 
3-> 

它是一個單鏈表,我感到困惑在哪裏把

cout<< endl; 

我無法聲明「#include string」或其他任何他對這個文件。

,如果我不喜歡這個

void printReverse(ListNode* p){ 
    if(!p) 
     return; 
    printReverse(p->next); 
    cout << (p->val) << "->"; 
    cout << endl; //LOOK AT HERE, DIFFERENCE IS HERE 
    return; 
} 

然後我的輸出是這樣的:

3-> 
2-> 
1-> 
3-> 
2-> 
3-> 

編輯:對於有人誰願意看到另一個輸出: MyOutput中:

5->6->7->8->9->5->6->7->8->5->6->7->5->6->5-> 

我想要的:

5->6->7->8->9-> 
5->6->7->8-> 
5->6->7-> 
5->6-> 
5-> 

這是主要的文件:

struct ListNode { 
    int val; 
    ListNode *next; 
    ListNode(int x) : val(x), next(NULL) {} 
}; 

int main(int argc, char const *argv[]){ 

    ListNode a(1); 
    ListNode b(2); 
    ListNode c(3); 
    a.next = &b; 
    b.next = &c; 

    ListNode* d = new ListNode(9); 
    ListNode* e = new ListNode(8); 
    ListNode* f = new ListNode(7); 
    ListNode* g = new ListNode(6); 
    ListNode* h = new ListNode(5); 

    d->next = e; 
    e->next = f; 
    f->next = g; 
    g->next = h; 
    // The Program continues to another functions 
    // .... 
    // In somewhere here the program calls reverseprint function 

    return 0; 
} 

EDIT2:我不能宣佈我的 「reverseprint.ccp」 提交的任何其他標題。這是規則。 EDIT3:第一預期輸出:

3->2->1-> 
3->2-> 
3-> 

是:

printReverse(a); 
printReverse(b); 
printReverse(c); 
// I believe it is like that. 
+1

I ndeed,如果你正在盯着寫在一張紙上的代碼,這可能會很棘手。但是你有一臺電腦在你面前,所以啓動一個調試器並*看*代碼需要去的地方! –

+0

'cout <<「\ n」'就在最後一次'return'之前;'?我編輯過的 –

+0

,如果我在最後一次返回之前發現<<「\ n」;它的確如上所述。我錯過了什麼,或者我應該做一些不同的事情? – doodley

回答

3

你應該使用 「的std ::名單」,並像

#include <iostream> 
#include <list> 

int main() 
{ 
    std::list<int> mylist; 
    for (int i=1; i<=5; ++i) mylist.push_back(i); 

    std::cout << "mylist backwards:"; 
    for (std::list<int>::reverse_iterator rit=mylist.rbegin(); rit!=mylist.rend(); ++rit) 
    std::cout << ' ' << *rit; 

    std::cout << '\n'; 

    return 0; 
} 

你一個反向迭代將有這樣的輸出:

mylist backwards: 5 4 3 2 1