Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Runtime: 8 ms, faster than 43.08% of C++ online submissions for Reverse 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* result = NULL;
while (head) {
ListNode* next = head -> next;
head -> next = result;
result = head;
head = next;
}
return result;
}
};
Runtime: 76 ms, faster than 89.64% of JavaScript online submissions for Reverse Linked List.
Memory Usage: 40.5 MB, less than 66.21% of JavaScript online submissions for Reverse Linked List.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let slow = null;
let p = head;
let temp;
while(p) {
temp = p.next;
p.next = slow;
slow = p;
p = temp;
}
return slow;
};