[leetcode - Bliend-75 ] 206. Reverse Linked List (Easy)

Given the head of a singly linked list, reverse the list, and return the reversed list.

给一个 linked list 将他反转。

Example

Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 5 -> 4 -> 3 -> 2 -> 1

Coding

/** * @param {ListNode} head * @return {ListNode} */var reverseList = function(head) {    let prev = null;    while (head) {        next = head.next;        head.next = prev;        prev = head;        head = next;    }    return prev; };

http://img2.58codes.com/2024/20124767ESRrBCybiC.jpg
创建一个 prev 指向 null

http://img2.58codes.com/2024/20124767mzyRMZBuUv.jpg
移动 next 到 head 的下一个 node

http://img2.58codes.com/2024/20124767mc9KolSoS4.jpg
将 head 的 next 连接到 prev

http://img2.58codes.com/2024/20124767AV8jyrwe1G.jpg
移动 prevhead (初始化 prev 指针)

http://img2.58codes.com/2024/20124767DF3CzPpEdR.jpg
移动 headnext (移动到下一个要处理的 node)

http://img2.58codes.com/2024/20124767crBYnfd9xt.jpg
移动 next 到下一个 node

http://img2.58codes.com/2024/201247674WFoBU8aSy.jpg
将 head 的 next 连接到 prev

http://img2.58codes.com/2024/20124767kbY8OEQKne.jpg
移动 prevhead (初始化 prev 指针)

http://img2.58codes.com/2024/20124767AhSvLcQXHN.jpg
移动 headnext (移动到下一个要处理的 node)

以此类推到 head 移动到 null。

http://img2.58codes.com/2024/vI8cfaH.gif

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章