206.reverse-linked-list.md 1.6 KB
Newer Older
L
luzhipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
## 题目地址
https://leetcode.com/problems/reverse-linked-list/description/

## 题目描述
Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

## 思路
这个就是常规操作了,使用一个变量记录前驱pre,一个变量记录后继next.

不断更新`current.next = pre` 就好了
## 关键点解析

- 链表的基本操作(交换)
- 虚拟节点dummy 简化操作
- 注意更新current和pre的位置, 否则有可能出现溢出


## 代码

```js
/*
 * @lc app=leetcode id=206 lang=javascript
 *
 * [206] Reverse Linked List
 *
 * https://leetcode.com/problems/reverse-linked-list/description/
 *
 * algorithms
 * Easy (52.95%)
 * Total Accepted:    532.6K
 * Total Submissions: 1M
 * Testcase Example:  '[1,2,3,4,5]'
 *
 * Reverse a singly linked list.
 * 
 * Example:
 * 
 * 
 * Input: 1->2->3->4->5->NULL
 * Output: 5->4->3->2->1->NULL
 * 
 * 
 * Follow up:
 * 
 * A linked list can be reversed either iteratively or recursively. Could you
 * implement both?
 * 
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    const dummyHead = {
        next: head
    }
    let current = dummyHead.next;
    let pre = null;

    while(current) {
        const next = current.next;
        current.next = pre;
        pre = current;
        current = next;
    }
    return pre;
};

```