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;
}
};