File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments