Reverse a singly linked list

Reverse a singly linked list.

 

 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         if (head == NULL){
13             return head;
14         }
15         ListNode *p1,*p2,*p3;
16         p1 = head;
17         p2 = p1->next;
18         if (p2 == NULL){
19             return head;
20         }
21         p3 = p2->next;
22         while (p2 != NULL){
23             p2->next = p1;
24             p1 = p2;
25             p2 = p3;
26             if (p3 != NULL){
27                 p3 = p3->next;
28             }
29         }
30         head->next = NULL;
31         return p1;
32         
33     }
34 };

 

posted @ 2015-05-07 15:10  george_cw  阅读(343)  评论(0编辑  收藏  举报