LeetCode-206. Reverse Linked List

来源:互联网 发布:南瑞信通 知乎 编辑:程序博客网 时间:2024/06/06 01:10

Reverse Linked List

Reverse a singly linked list.

/** * 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===null) return null;    if(head.next===null) return head;    var p=head.next;    var q=reverseList(p);    head.next=null;    p.next=head;    return q;};
/** * 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===null||head.next===null) return head;    var p=head;    var q=head.next;    p.next=null;    var tmp;    while(q!==null){        tmp=q.next;        q.next=p;        p=q;        q=tmp;    }    return p;};