需求
写入一个函数,输入一个链表,反转链表后,输出新链表的表头
分析
输入的是一个链表,返回的是一个头节点
可以选择先遍历链表取出其中的值放入数组中,然后将数组的值倒序插入到链表里
或者不改变值而是改变链表的指向来达成目的
代码
遍历取值再更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function ListNode(val) { this.val = val; this.next = null; }
function createList(arr) { while (arr.length) { let nodeval = arr.shift(); let head = new ListNode(nodeval); head.next = createList(arr); return head; } return null; }
function reverseList(head){ let p = head; let arr = []; while(p){ arr.push(p.val); p = p.next; } p = head; while(p){ p.val = arr.pop(); p = p.next; } return head; } let arr = [1,2,3,4,5,6,7,8]; let head = createList(arr); console.log(reverseList(head));
|
改变指向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| function ListNode(val) { this.val = val; this.next = null; }
function createList(arr) { while (arr.length) { let nodeval = arr.shift(); let head = new ListNode(nodeval); head.next = createList(arr); return head; } return null; } function reverseList(head){ let p = null; while(head){ let n = head.next; head.next = p; p = head; head = n; } return p; }
|