C++ Lists

E

EcLipSe-X

I need to create a List and write a function that takes this list as
argument, to find the middle node, and delete it from the list. The
function should return the new list. Is there anyone who can help?
Regards!
 
A

Alan Johnson

EcLipSe-X said:
I need to create a List and write a function that takes this list as
argument, to find the middle node, and delete it from the list. The
function should return the new list. Is there anyone who can help?
Regards!

If you just need a list, use std::list
(http://www.sgi.com/tech/stl/List.html)

If you need to do this for a homework assignment or such, then go to
Google and search for something like "Linked List tutorial". That
particular search phrase turns up quite a few decent examples of linked
lists.

-Alan
 
R

Robbie Hatley

EcLipSe-X said:
I need to create a List

std::list said:
and write a function that takes this list as
argument, to find the middle node, and delete it from the list. The
function should return the new list. Is there anyone who can help?
Regards!

std::list<MyType> & MyFunc (std::list<MyType> & List)
{
// do stuff to List
return List;
}

Hint: to find middle node, use a for() loop and a
std::list<MyType>::iterator to iterator through the
list, and count nodes. Then start over at beginning,
iterator half the node count, erase the node.

The details are for the student to work out. Try
scrutinizing the "references", "standard containers",
and "iterators" chapters of your C++ book.


(Or, you could build your list from scratch using pointers,
malloc(), and free(); but that's the C way of doing it,
not the C++ way.)

--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
 
J

Jason Heyes

EcLipSe-X said:
I need to create a List and write a function that takes this list as
argument, to find the middle node, and delete it from the list. The
function should return the new list. Is there anyone who can help?
Regards!

#include <iterator>
#include <list>

template <typename T>
void erase_middle(std::list<T> &lst)
{
typedef typename std::list<T>::iterator ListIterator;

if (lst.empty())
return;

ListIterator it = lst.begin();
std::advance(it, lst.size() / 2);
lst.erase(it);
}

template <typename T>
std::list<T> erase_middle_copy(std::list<T> lst)
{
erase_middle(lst);
return lst;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,298
Messages
2,571,542
Members
48,283
Latest member
RitaVui655

Latest Threads

Top