1 使用固定量的存储空间
2 主要思想是头插法,重复执行
“第二个元素插入到第一个元素之前,迭代第二个元素”
1 #include <iostream> 2 #include <crtdbg.h> 3 #include <cstring> 4 using namespace std; 5 6 typedef int DataType; 7 //建立链表 8 class list 9 { 10 private: 11 struct Node 12 { 13 DataType data; 14 Node* next; 15 }; 16 Node *head;//哨兵位 17 public: 18 list() 19 { 20 Init(); 21 } 22 ~list() 23 { 24 Delete(); 25 } 26 void Init(); 27 void Delete(); 28 void Insert(const DataType data); 29 void Print(); 30 bool Empty() { return head->next == NULL;} 31 void ReversedSort(); //就地逆序 32 }; 33 void list::Init() 34 { 35 head = new Node; 36 head->next = NULL; 37 } 38 void list::Delete() 39 { 40 for(Node *p=head; p != NULL;) 41 { 42 Node *pTemp = p->next; 43 delete p; 44 p = pTemp; 45 } 46 head = NULL; 47 } 48 //头插法 49 void list::Insert(const DataType data) 50 { 51 Node *pNew = new Node; 52 pNew->data = data; 53 pNew->next = head->next; 54 head->next = pNew; 55 } 56 void list::Print() 57 { 58 for (Node *p = head->next; p != NULL; p = p->next) 59 { 60 cout << p->data << endl; 61 } 62 } 63 //就地逆序 64 void list::ReversedSort() 65 { 66 Node *pOne = head->next; 67 Node *pTwo = pOne->next; 68 Node *pFirst = NULL; 69 70 while(pOne != NULL) 71 { 72 // 第二项变第一项,第一项连接第三项 73 pFirst = head->next; 74 head ->next = pTwo; 75 pOne->next = pTwo->next; 76 pTwo->next = pFirst; 77 78 if (pOne->next != NULL) 79 { 80 pTwo = pOne->next; 81 } 82 else 83 { 84 break; 85 } 86 } 87 } 88 89 int main() 90 { 91 //检测是否有内存泄露 需要加头文件#include <crtdbg.h> 92 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); 93 94 list l; 95 96 for (int i=10; i>0; --i) 97 { 98 l.Insert(i); 99 } 100 101 l.Print(); 102 103 l.ReversedSort(); 104 105 l.Print(); 106 107 system("pause"); 108 return 0; 109 }
10.2-7 单链表的就地逆置,布布扣,bubuko.com
原文:http://www.cnblogs.com/sevenPP/p/3665276.html