单向链表反转 2022-02-22 周二

2022-02-22  本文已影响0人  松哥888

基本思路

C代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head) {
    // 判空
    if (head == NULL) {
        return NULL;
    }

    // 三个指针
    struct ListNode *current = head;
    struct ListNode *previous = NULL;
    struct ListNode *next = NULL;
    
    // 反转
    while(current != NULL) {
        next = current->next;
        current->next = previous;
        previous = current;
        current = next;
    }
    
    // 返回反转后的新头
    return previous;
}

JS代码

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    // 判空
    if (!head) {
        return null;
    }

    // 三个指针
    let previous = null;
    let current = head;
    let next = null;

    // 反转
    while (current) {
    // 保存next
    next = current.next;
    // 替换next
    current.next = previous;
    // 设置pre的值
    previous = current;
    // 设置当前项的值
    current = next;
    }
      
    return previous;
};

Swift代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        // 判空
        if head == nil {
            return nil
        }

        // 三个指针
        var current = head
        var previous : ListNode? = nil
        var next : ListNode? = nil

        // 反转
        while current != nil {
            next = current?.next
            current?.next = previous
            previous = current
            current = next
        }

        // 返回新的head
        return previous
    }
}

简单比较

性能差距

参考文章

看一遍就理解,图解单链表反转

C代码

JS代码

Swift代码

上一篇 下一篇

猜你喜欢

热点阅读