2016-12-02 32 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