Skip to content

Commit 2ab0ddf

Browse files
committed
reverse-linked-list
1 parent 983ddb4 commit 2ab0ddf

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

reverse-linked-list/taewanseoul.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 206. Reverse Linked List
3+
* Given the head of a singly linked list, reverse the list, and return the reversed list.
4+
*
5+
* https://leetcode.com/problems/reverse-linked-list/description/
6+
*
7+
*/
8+
9+
/**
10+
* Definition for singly-linked list.
11+
* class ListNode {
12+
* val: number
13+
* next: ListNode | null
14+
* constructor(val?: number, next?: ListNode | null) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.next = (next===undefined ? null : next)
17+
* }
18+
* }
19+
*/
20+
21+
class ListNode {
22+
val: number;
23+
next: ListNode | null;
24+
constructor(val?: number, next?: ListNode | null) {
25+
this.val = val === undefined ? 0 : val;
26+
this.next = next === undefined ? null : next;
27+
}
28+
}
29+
30+
// O(n) time
31+
// O(1) space
32+
function reverseList(head: ListNode | null): ListNode | null {
33+
let prev: ListNode | null = null;
34+
let next: ListNode | null = null;
35+
36+
while (head) {
37+
next = head.next;
38+
head.next = prev;
39+
40+
prev = head;
41+
head = next;
42+
}
43+
44+
return prev;
45+
}

0 commit comments

Comments
 (0)