Skip to content

Commit

Permalink
add: 206 js solution added
Browse files Browse the repository at this point in the history
  • Loading branch information
royIdoodle committed Jul 19, 2019
1 parent 08e085a commit 59c18d4
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion docs/Algorithm/Leetcode/JavaScript/0206._Reverse-Linked-List.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,54 @@ var reverseList = function(head) {
return nodeList[nodeList.length - 1]
};

```
```



* 思路2: 迭代法

使用`parentNode`缓存上次循环的结果,每次循环都生成两个新的`ListNode`用来翻转链表各个元素,一次迭代即可完成链表反转。

> 思路
> **- 时间复杂度: O(N)**
>
> **- 空间复杂度: O(1)**
> 执行用时 :**116 ms**, 在所有 JavaScript 提交中击败了**20.19%**的用户
>
> 内存消耗 :**35.5 MB**, 在所有 JavaScript 提交中击败了**14.78%**的用户
```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) {
return head
}
let parentNode = null
while (head) {
let current = new ListNode(head.val)
current.next = parentNode
if (head.next) {
let next = new ListNode(head.next.val)
next.next = current
} else {
let next = null
return current
}
parentNode = current
head = head.next
}
return head
};
```

0 comments on commit 59c18d4

Please sign in to comment.