This paper demonstrates the reverse method of C + + by an example, and has a good reference value for the learning of C + + data structure. The specific methods are as follows:
First of all, C + + list of reverse the difficulty lies in how to modify one by one. Although not an array, but presumably the idea is the same, so you can use a for sequential, a cursor for the loop inside of the I, but to remember the previous node and the next node, especially the latter, because after the modification is not access to the back, so to record. For Each loop only changes the pointer to the node to which it is pointed, so that it will not be messed up.
With a For loop it's very good to understand that the instance code looks like this:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std;
Linked list node class Node {Private:int m_data;
node* M_next; Node (node&) {}//copy constructor is not allowed public:explicit node (int val = 0): M_data (Val), M_next (NULL)
{} int getData () const {return m_data}
void SetData (int val) {m_data = val;}
node* getNext (void) const {return m_next;}
void Setnext (node* p) {m_next = P;}}; Linked List class MyList {private:node* m_head; Pionter to the the list node* m_tail; Poinoer to the last node of the list MyList (mylist&) {} public:explicit MyList (): M_head (null), M_tail (NULL)
{} void AddNode (node* pnode);
void Show (void) const;
void reverse (void);
void clean (void);
};
void Mylist::addnode (node* pnode) {if (m_head) {m_tail->setnext (pnode);
M_tail = Pnode;
else//blank list {m_head = Pnode;
M_tail = Pnode; } void Mylist::show (void) const
{node* pnode = M_head;
while (Pnode) {std::cout << pnode->getdata () << "";
Pnode = Pnode->getnext (); } void Mylist::reverse (void) {node* prenode = NULL; The previous node* Pnode of the following cursor; Point to each node, equivalent to a cursor node* afternode; The previous for (Pnode = m_head; pnode!= NULL; pnode = afternode)//Every loop here corresponds to a node, essentially an array of principles {Afternode = Pnod
E->getnext ();
Pnode->setnext (Prenode);
Prenode = Pnode; } pnode = M_head;
Swap the ends of the pointer m_head = M_tail;
M_tail = Pnode;
} void Mylist::clean (void) {if (m_head) {node* pnode = M_head;
node* ptemp;
while (pnode) {ptemp = Pnode->getnext ();
Delete Pnode;
Pnode = ptemp;
} m_head = M_tail = NULL;
int main (void) {MyList listhead;
Srand ((unsigned) time (NULL));
for (int i = 0; i < 9; i++) {int temp = rand ()% 50;
node* pnode = new Node (temp);
Listhead.addnode (Pnode);
} listhead.show (); Listhead.reverSE ();
cout << Endl;
Listhead.show ();
Listhead.clean ();
Listhead.show ();
System ("pause");
}
I believe the example of this article for everyone to learn C + + data structure and algorithms can play a reference role.