题目描述
输入一个链表,反转链表后,输出新链表的表头。
分析
典型的面试题以及大学数据结构课程常见题,没啥好分析的了...
代码实现
递归版
function ListNode(x){ this.val = x; this.next = null;}function ReverseList(h){ if(h === null || h.next === null) return h; var reversedHead = ReverseList(h.next); h.next.next = h; h.next = null; return reversedHead;}
非递归版
function ListNode(x){ this.val = x; this.next = null;}function ReverseList(h){ if(h === null || h.next === null) return h; var pre = null; var cur = h; while(cur !== null) { var next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre;}