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 };

 

posted @ 2017-10-24 17:00  绿宝宝怪  阅读(114)  评论(0编辑  收藏  举报
#site_nav_under,#ad_under_post_holder,#under_post_news,#google_ad_c2,#under_post_kb{ width:0; height:0; display:none; overflow:hidden; }