206. Reverse Linked List 反转链表
206. Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseList(ListNode* head) { 12 ListNode* pReversedHead = nullptr; 13 ListNode* pNode = head; 14 ListNode* pPrev = nullptr; 15 while(pNode != nullptr) 16 { 17 ListNode* pNext = pNode->next; //record pNext 18 if (pNext == nullptr) // pReversedHead 19 pReversedHead = pNode; 20 pNode->next = pPrev; // reverse 21 pPrev = pNode; 22 pNode = pNext; 23 } 24 return pReversedHead; 25 } 26 };