标签:
单链表反转笔记:
1 #include<iostream> 2 #include<string.h> 3 using namespace std; 4 5 struct ListNode 6 { 7 int val; 8 ListNode* next; 9 ListNode(int i):val(i),next(NULL){}; 10 }; 11 void printList(ListNode* myList) 12 { 13 while(myList != NULL) 14 { 15 cout << myList -> val << "->"; 16 myList = myList -> next; 17 } 18 cout << "NULL" << endl; 19 } 20 ListNode* reverseList(ListNode* pHead) 21 { 22 23 if(pHead == NULL) return pHead; 24 ListNode* pre = NULL; 25 ListNode* cur = pHead; 26 while(cur != NULL) 27 { 28 ListNode* newpre = cur; 29 ListNode* newcur = cur -> next; 30 cur -> next = pre; 31 cur = newcur; 32 pre = newpre; 33 } 34 return pre; 35 } 36 int main() 37 { 38 ListNode* pHead = new ListNode(0); 39 ListNode* cur = pHead; 40 for (int i = 1; i < 10; ++i) 41 { 42 ListNode* newNode = new ListNode(i); 43 cur -> next = newNode; 44 cur = cur -> next; 45 } 46 printList(pHead); 47 printList(reverseList(pHead)); 48 return 0; 49 }
标签:
原文地址:http://www.cnblogs.com/90zeng/p/cpp_reverse_list.html