我需要一些帮助,我需要能够在链表中找到一个元素并在列表中向下移动。我怎么能这样做?
例如: 1 2 3 4
找到2并切换到下一个
输出:1 3 2 4
向下移动两个空格 2 3 4 1
答案 0 :(得分:1)
如果你正在使用std::list
,这很简单。首先,搜索您的号码,让您获得列表中该位置的迭代器。例如:
std::list<int> mylist;
//populate your list with the digits you want
//find the element in the list
int element = 5;
std::list<int>::iterator current = mylist.begin();
for (; current != mylist.end(); current++)
{
if (*current == element)
break;
}
//Now move your element two positions back (let's assume you have the elements in
//the list to-do that amount of movement, but nevertheless,
//we still check the list bounds and exit the loop if we hit the front of the list)
for (std::list<int>::iterator new_position = current, int i=0;
(i < 2 && new_position != mylist.begin());
i++, new_position--);
mylist.insert(new_position, 1, *current);
//erase where the element used to be
mylist.erase(current);
如果您没有使用std::list
,请使用std::list
: - )