In reverse order, the difficulty lies in how to modify them one by one. Although it is not an array, the general idea is the same, so you can use a for sequence, a cursor corresponds to the I in the for loop, but remember the previous node and the next node, in particular, the last one should be recorded because it cannot be accessed after modification. For each loop only changes the pointer to the node.
I am very familiar with using a for loop. I used to use while to confuse myself with my computer...
# Include <iostream> # include <cstdlib> # include <ctime> using namespace STD; // class node of the linked list node {PRIVATE: int m_data; node * m_next; node (node &) {}// copy constructor is not allowedpublic: 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 first node of 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 // BL Ank 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 cursor below; // points to each node, which is equivalent to the cursor node * afternode; // The previous for (pnode = m_head; pnode! = NULL; pnode = afternode) // each cycle here corresponds to a node, essentially similar to the array principle {afternode = pnode-> getnext (); pnode-> setnext (prenode ); prenode = pnode;} pnode = m_head; // switch head and tail 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 ");}