顾名思义, 就是将链表的所有结点反转。
代码:
#include <iostream> struct NodeList { int data; struct NodeList* next; NodeList() :data(0), next(NULL) {} NodeList(int data) :data(data), next(NULL) {} NodeList(int data,NodeList *next) :data(data), next(next) {} }; class Solution { public: void add(NodeList* head, int dat) { NodeList* newnode = new NodeList(); newnode->data = dat; newnode->next = NULL; NodeList* node = head; while (node->next != NULL) { node = node->next; } node->next = newnode; } NodeList *reverse(NodeList* head) { NodeList* node = head; NodeList* temp = NULL; NodeList* reverhead = NULL; NodeList* pnext = NULL; while (node != NULL) { pnext = node->next; if (pnext == NULL) { reverhead = node; } node->next = temp; temp = node; node = pnext; } return reverhead; } void print(NodeList* head) { NodeList* node = head; while (node!= NULL) { std::cout << node->data << " "; node = node->next; } std::cout << std::endl; } }; int main() { Solution s; NodeList* node = new NodeList(1,NULL); for (int i = 2; i < 11; i++) { s.add(node, i); } s.print(node); NodeList *revernode = s.reverse(node); s.print(revernode); return 0; }
打印:
1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1