#include <iostream> #include <vector> #include <queue> using namespace std; struct LinkedListNode{ int value; LinkedListNode *pNext; LinkedListNode(int v) : value(v) {} }; //创建链表 LinkedListNode *CreateLinkedList(int arr[], int len) { LinkedListNode *pHead = new LinkedListNode(arr[0]); LinkedListNode *pPre = pHead; LinkedListNode *pCurr = NULL; //每次进入该循环的时候,pPre是起作用的 //pCurr都会重新构造一个LinkedListNode for (int i = 1; i < len; i++) { pCurr = new LinkedListNode(arr[i]); pCurr->pNext = NULL; pPre->pNext = pCurr; pPre = pCurr; } return pHead; } //输出链表 void PrintLinkedList(LinkedListNode *pHead) { while (pHead) { cout<<pHead->value<<endl; pHead = pHead->pNext; } } //反转链表 //需要3个指针,pCurr指向正在改变的Node,pPre指向需要改变到的位置,pNex记录不再被pCurr指向的下一个位置 LinkedListNode *ReverseLinkedList(LinkedListNode *pHead) { if (!pHead) return NULL; LinkedListNode *pPre = NULL; LinkedListNode *pCurr = pHead; LinkedListNode *pNex = pHead->pNext; while (pCurr) { pCurr->pNext = pPre; pPre = pCurr; pCurr = pNex; if (pNex)//当pCurr为最后一个元素的时候,pNex已经为NULL,所以需要check pNex = pNex->pNext ? pNex->pNext : NULL; } return pPre; } int main() { int arr[10] = {4, 2, 5, 7, 4, 1, 7, 3, 1, 9}; LinkedListNode *pHead = CreateLinkedList(arr, 10); PrintLinkedList(pHead); pHead = ReverseLinkedList(pHead); cout<<endl<<"After Reverse:"<<endl; PrintLinkedList(pHead); return 0; }
EOF