单向链表的反转
#include <iostream> #include <list> #include <vector> using namespace std; class ListNode { public: ListNode *next; int data; }; ListNode* reverse(ListNode * head) { ListNode *pCur, *pPrev, *pNext; pPrev = NULL; pCur = head; while (pCur != NULL) { pNext = pCur->next; pCur->next = pPrev; pPrev = pCur; pCur = pNext; } return pPrev; } void travelList(ListNode* head) { ListNode *cur = head; while (cur != NULL) { cout << "node: " << cur->data << endl; cur = cur->next; } } int main() { ListNode *head = NULL, *cur = NULL; for (int i = 0; i < 10; i++) { ListNode * temp = new ListNode; temp->data = i; temp->next = NULL; if (cur == NULL) { cur = temp; head = temp; } else { cur->next = temp; cur = temp; } } cout << "beafore reverse:" << endl; travelList(head); cout << "================== end =================" << endl; cout << "after reverse:" << endl; cur = reverse(head); travelList(cur); cout << "================== end =================" << endl; vector<int> testV; list<int> testL; return 0; }