?struct ListNode { ?????????int? val; ?????????ListNode *next; ?????????ListNode() : val(0), next(nullptr) {} ?????????ListNode(int x) : val(x), next(nullptr) {} ?????????ListNode(int x, ListNode *next) : val(x), next(next) {} };
?// iteratively
// iteratively
? ListNode* reverseList(ListNode* head) { ? ? ? ? if(head == NULL || head->next == NULL) ???????? ? ?return head;
????????ListNode * pPrevious = NULL;
????????ListNode * pCurrent = head;
????????ListNode * pNext = head->next;
??????while( pNext){
??????????pCurrent->next = pPrevious; ? ? ? ? ? pPrevious = pCurrent; ??????????pCurrent = pNext; ? ? ? ? ? pNext = pNext->next; ??????????pCurrent->next = pPrevious; ??????????? ????}
????return pCurrent; ? ? }
//?recursion
?ListNode* reverseList(ListNode* head) { ? ? ? ? if(head == NULL || head->next == NULL) ? ? ? ? ? ? return head; ? ? ? ? ListNode* last = reverseList(head->next); ? ? ? ? head->next->next = head; ? ? ? ? head->next = NULL; ? ? ? ? ? ?? ? ? ? ? return last; ? ? }
|