Skip to content

Commit fdc949c

Browse files
committed
feat : reverse-linked-list
1 parent c636ff2 commit fdc949c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

reverse-linked-list/ekgns33.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*
11+
*
12+
* input : head of linked list
13+
* output : reversed linked list
14+
*
15+
* solution1)
16+
* set fast pointer and slow pointer
17+
* iterate through the linked list
18+
* set fast pointer's next to slow pointer
19+
*
20+
* tc : O(n)
21+
* sc : O(1)
22+
*/
23+
class Solution {
24+
public ListNode reverseList(ListNode head) {
25+
if(head == null) return head;
26+
ListNode curr = head;
27+
ListNode prev = null;
28+
while(curr.next != null) {
29+
ListNode next = curr.next;
30+
curr.next = prev;
31+
prev = curr;
32+
curr = next;
33+
}
34+
curr.next = prev;
35+
return curr;
36+
}
37+
}

0 commit comments

Comments
 (0)