Reverse Linked List

Reverse a singly linked list.

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL)
            return NULL;
            
        ListNode* node;
        node = (ListNode*)malloc(sizeof(ListNode*));
        node->next = NULL;
        
        while(head){
            ListNode* ptr = head;
            head = head->next;
            ptr->next = node->next;
            node->next = ptr;
            
        }
        return node->next;
    }
};

 

posted on 2015-08-30 11:23  horizon.qiang  阅读(121)  评论(0编辑  收藏  举报

导航