开发者

Help with doubly Linked List in C++

开发者 https://www.devze.com 2023-03-07 04:46 出处:网络
so I am having a little trouble wrapping my head around this problem. I have created a doubly linked list called dlist (which contains a linknode helper class). I have another class called DeckOps tha

so I am having a little trouble wrapping my head around this problem. I have created a doubly linked list called dlist (which contains a linknode helper class). I have another class called DeckOps that is used along with the linked list. dlist already contains functions to insertFront, removeFront, insertRear, removeRear and a print function. Currently I have it working where I pass a filename to DeckOps, which then reads in a file, inputing an int into each link node of the list (putting in from rear to hold same order as in the file).

Now my problem, I need to be able to find a number in the list, so I assume I will need a find function. and then I need to be able to select everything below a number 开发者_如何学Cand swap it with everything above a number. a seperate swap function would be nice i think? My main issue here is how to select a group and swap with another group.

thanks

example: 1 2 3 4 5 6 7 8 9 find 6 find 4 swap everything below 6, with everything above 4 7 8 9 4 5 6 1 2 3 result EDIT: just realized in writing out this example is the program needs to know if the number i search for is closer to the top or to the bottom.

not looking for a solution, just some help.


Just curios ... is there any reason not to use an STL container class?

Do you really need to reinvent the wheel? Do you have a requirement that you think STL can't handle? Do you think you can code "better" then the STL? Are you perhaps coding for an embedded device or obscure processor with no STL support?

Even if not STL, did you consider Boost++ ?

You may be asking the wrong question here ... perhaps you should be asking yourself if can spare time from the rest of your development to reinvent the wheel.


If I correctly interpret what you mean by "swap", you need to implement list splicing. You can either move the range at the start to a new list, then move it back to the end of the original list, or you can do it all at once. The latter is only slightly more complicated, mostly in terms of preconditions that the insertion point isn't within the range to be moved.

Example with std::list:

int main() {
  std::list<int> L;
  for (int n = 0; n != 10; ++n) L.push_back(n);
  std::list<int>::iterator x = std::find(L.begin(), L.end(), 6);
  assert(x != L.end());  // We know this is true in this example.

  std::list<int> temp;
  temp.splice(temp.end(), L, L.begin(), x);
  temp.splice(temp.begin(), L, x);
  L.splice(L.end(), temp);

  std::copy(L.begin(), L.end(), std::ostream_iterator<int>(std::cout, ", "));

  return 0;
}

Output:

  7, 8, 9, 6, 0, 1, 2, 3, 4, 5, 
# ^-----^     ^--------------^
#   \... swapped with .../
0

精彩评论

暂无评论...
验证码 换一张
取 消