16 Reverse a singly linked list

Input a linked list, after reversing the linked list, output all elements of the linked list.

 

C++:

 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6        val(x), next(NULL) {
 7     }
 8 };*/
 9 class Solution {
10 public:
11     ListNode* ReverseList(ListNode* pHead) {
12         ListNode* p = NULL ;
13         while(pHead != NULL){
14             ListNode* pNext = pHead->next ;
15             pHead->next = p ;
16              p = pHead;
17              pHead = pNext;
18          }
 19          return p;
20      }
 21 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820512&siteId=291194637