在列表 c++ 中向下移动元素

发布于 2024-11-08 19:20:59 字数 141 浏览 0 评论 0原文

我需要一些帮助,我需要能够在链接列表中找到一个元素并将其在列表中向下移动。我该怎么做?

例子: 1 2 3 4

找到 2 并切换到下一个

输出: 1 3 2 4

将 2 向下移动两个空格 2 3 4 1

I need some help, I need to be able to find an element in a linked list and move it down in the list. How can I do this?

example:
1 2 3 4

find 2 and switch with next

output: 1 3 2 4

move 2 two spaces down
2 3 4 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似狗非友 2024-11-15 19:20:59

如果您使用 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 :-)

If you're using std::list, this is fairly simple. First, do a search for your number, getting you an iterator to that position in the list. For example:

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);

And if you're not using std::list, use std::list :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文