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.

您应该使用" std :: list"和一个像这样的反向迭代器

#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

最新更新