206. Reverse Linked List

 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/* acception of mine*/
/*
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL) return head;
        ListNode* q = NULL;
        ListNode* p = head->next;
        if (p == NULL) return head;
        head->next = NULL;
        while(p != NULL){
            q = p->next;
            p->next = head;
            head = p;
            p = q;
        }
        return head;
    }
};
*/
/* Acception of mine2 better one!*/
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = NULL;
    ListNode* q;
        while(head)
        {
            q = head->next;
            head->next = pre;
            pre = head;
            head = q;
        }
        return pre;
    };

};




Guess you like

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