2017-10-28 94 views
-1

我有一个函数,将随机整数插入到列表中,并显示列表的函数。我现在有什么,有没有办法显示该列表反向?如何反转显示链接列表?

void InsertRandomInts() 
{ 
LinkedSortedList<int> list; 
srand((unsigned)time(NULL)); 

for (int i = 0; i < 50; ++i) 
{ 
    int b = rand() % 100 + 1; 
    list.insertSorted(b); 
}  
displayListForward(&list); 

} 


void displayListForward(SortedListInterface<int>* listPtr) 
{ 
cout << "The sorted list contains " << endl; 
for (int pos = 1; pos <= listPtr->getLength(); pos++) 
{ 
    cout << listPtr->getEntry(pos) << " "; 
} 
cout << endl << endl; 
} 

回答

0

一个很好的想法是摆脱非标准通用容器,转而使用std::list(或者真的只是std::vector如果你不需要特定列表的语义如能删除一个元素而不会将迭代器赋予其他元素)。

sort成员函数可以在添加所有项目后应用。最后,您可以使用rbeginrend进行反向迭代。

下面是一个简单的例子:

#include <iostream> 
#include <list> 
#include <cstdlib> 
#include <ctime> 

void DisplayListForward(std::list<int>& list) 
{ 
    std::cout << "The sorted list contains\n"; 

    for (auto iter = list.rbegin(); iter != list.rend(); ++iter) 
    { 
     std::cout << *iter << " "; 
    } 
    std::cout << '\n'; 
} 

void InsertRandomInts() 
{ 
    std::list<int> list; 
    std::srand(static_cast<unsigned>(std::time(nullptr))); 

    for (int i = 0; i < 50; ++i) 
    { 
     auto const b = std::rand() % 100 + 1; 
     list.push_back(b); 
    } 

    list.sort(); 

    DisplayListForward(list); 
} 

int main() 
{ 
    InsertRandomInts(); 
} 

但是这可能是矫枉过正;对于快速解决方案,只需将您的当前循环颠倒过来:

for (int pos = listPtr->getLength(); pos >= 1; pos--) 
+0

为了我需要做的事情,我将采取快速解决方案。谢谢。 –

2

将列表从rbegin()复制到rend()并打印出来。您将反向打印它。

要么1)停止重新发明轮子,只使用具有这些功能的标准容器。或2)为您的自定义容器实现rbegin()& rend()。

for (auto it = list.rbegin(); it != it.rend(); ++it) 
    // Print *it 
+0

在代码中看起来如何?这听起来像我正在用印刷前进。 –

+0

OP不使用标准容器。没有'rbegin'和'rend' ... –

+0

@Christian Hackl然后OP可以1)停止重新发明轮子,只是使用标准容器。或者2)为他的自定义容器实现'rbegin()'&'rend()'。 –