码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Linked List

时间:2015-10-25 06:06:38      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

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;

[LeetCode] Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/agentgamer/p/4908120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!