LeetCode #10
What I’ve Learned
First, when reversing the LinkedList, you can define the after
variable inside while
loop.
Disclaimer
My LeetCode is free plan. I am posting just the free algorithms for now on. Also, I am using JAVA to code.
344. Reverse String
My Solution
I solved this problem and the solution was clear. I wasn’t able to come up with 2 pointers but I didn’t see the solutions. I am proud.
class Solution {
public void reverseString(char[] s) {
char temp = 'a';
for(int i =0; i<s.length/2;i++) {
temp = s[i];
s[i] = s[s.length-1-i];
s[s.length-1-i]= temp;
}
}
}
206. Reverse Linked List
My Solution
I’ve saw this problem in Udemy. I know how to do it but I wasn’t able to fix it due to the return
. Also, defining ListNode after = temp.next;
is a good idea I think.
class Solution {
public ListNode reverseList(ListNode head) {
ListNode before = null;
ListNode temp = head;
while(temp != null){
ListNode after = temp.next;
temp.next = before;
before = temp;
temp = after;
}
return before;
}
}
141. Linked List Cycle
My Solution
I’ve also saw this question in Udemy. I thought it would be easy to solve, but the problem was using while
loop.
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if(head == null) return false;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast) return true;
}
return false;
}
}