Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

反转链表 #11

Open
Aras-ax opened this issue Mar 6, 2019 · 0 comments
Open

反转链表 #11

Aras-ax opened this issue Mar 6, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Mar 6, 2019

反转一个单链表。

示例:

输入: 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) {
    let last,
        next = head;

    while(next){
        next = head.next;
        head.next = last;
        last = head;
        head = next ? next : head;
    }

    return head;
};

// 递归
function reverseList(head) {
    if (head === null) {
        return null;
    }

    return reverse(head);
}

function reverse(head, last) {
    if (head) {
        let next = head.next;
        head.next = last;
        last = head;
        return reverse(next, last);
    }
    return last;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant