Reverse a singly linked list.
将第一个节点作为当前节点,将当前节点的下一个存下来,当前节点的下一个节点指向前一个节点,当前节点作为前一个节点,将刚才存下的下一个节点作为当前节点。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
var prev = null;
while (head!==null) {
var next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
};