leetcode题解-JavaScript 206. 链表反转 Reverse Linked List (Easy)

LeetCode题解-JavaScript

  • 206. 链表反转 Reverse Linked List (Easy)
    • 题目代码(JavaScript )

206. 链表反转 Reverse Linked List (Easy)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

题目代码(JavaScript )

两种方法

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

//法二
var reverseList = function(head) {
    if(head==null || head.next==null){
        return head;
    }
    var list = head;
    var p = list;
    var q= null;
    while(p.next!=null) {
        q = p.next;
        p.next = q.next;
        q.next = list;
        list = q;     
    }
    return list;
}

你可能感兴趣的:(leetcode题解-JavaScript 206. 链表反转 Reverse Linked List (Easy))