206. Reverse Linked List

2018-08-14  本文已影响0人  SilentDawn

Problem

Reverse a singly linked list.

Example

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL)
            return NULL;
        ListNode *newhead = new ListNode(0);
        while(head){         
            ListNode *temp = new ListNode(head->val);
            temp->next = newhead->next;
            newhead->next = temp;
            head=head->next;
        }
        return newhead->next;
    }
};

Result

206. Reverse Linked List.png
上一篇 下一篇

猜你喜欢

热点阅读