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){
        ListNode* newHead = new ListNode(-1);
        ListNode* cur = head;
        while(cur){
            ListNode* newHead_next = newHead->next;
            ListNode* next = cur->next;
            newHead->next = cur;
            cur->next = newHead_next;
            cur = next;
        }
        return newHead->next;
    }
};

 

posted @ 2016-10-02 20:56  wxquare  阅读(105)  评论(0编辑  收藏  举报