[LeetCode] Reverse Linked List
Reverse a singly linked list.
这题因为palindrome linked list 的时候需要就顺便做了一下。利用三个指针:prev, now, next 相互倒腾就行。
/** * 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 null; var prev = null; var now = head; var next = head.next while (now) { now.next = prev; prev = now; now = next; if (next) next = next.next; } return prev; };
还可以递归的解决。算法2:
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseHelp = function(head) { if (!head.next) return head; reverseHelp(head.next).next = head; return head; } var reverseList = function(head) { if (!head) return null; var tail = head; while (tail.next) { tail = tail.next; } reverseHelp(head).next = null; return tail; };
但是问题是翻转以后,原来的尾巴变成了头,我没有想到太好的递归方法,就先遍历了一遍找到尾,然后再用递归的翻转head。
第一次提交的时候出现了bug,原因是递归过程 reverseHelp 是返回链表尾,所以最后别忘了把他最终返回的链表尾巴.next = null;