Leetcode 206——反转字符串
分递归和非递归,代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { //ListNode *pResult = reverseCoreRecursively(head); ListNode *pResult = reverseCoreLoop(head); return pResult; } ListNode* reverseCoreLoop(ListNode *pNode) { if (pNode == nullptr) return nullptr; ListNode *pNewHead = pNode; pNode = pNode->next; pNewHead->next = nullptr; while (pNode != nullptr) { ListNode *pTempNewHeadNode = pNode; pNode = pNode->next; pTempNewHeadNode->next = pNewHead; pNewHead = pTempNewHeadNode; } return pNewHead; } ListNode* reverseCoreRecursively(ListNode* pNode) { if (pNode == nullptr) return nullptr; if (pNode->next == nullptr) return pNode; ListNode *pCurNode = reverseCoreRecursively(pNode->next); ListNode *pTempNode = pCurNode; while(pTempNode->next != nullptr) { pTempNode = pTempNode->next; } pTempNode->next = pNode; pNode->next = nullptr; return pCurNode; } };
感觉递归的代码还可以优化