**定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL**
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if (!head) {
return head;
}
let temp = [];
while (head) {
temp.push(head.val);
head = head.next;
}
temp = temp.reverse();
const newHead = {
val: temp[0],
next: null
};
node = newHead;
for (let i = 1; i < temp.length; i++) {
node.next = {
val: temp[i],
next: null
};
node = node.next;
}
return newHead;
};
console.log(reverseList);