LeetCode – Reorder List (Java)

Given a singly linked list L: L0→L1→ … →Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… For example, given {1,2,3,4}, reorder it to {1,4,2,3}. You must do this in-place without altering the nodes’ values. Java Solution Because the problem requires “in-place” operations, we can only change their pointers, not creating a new list. This problem can be solved … Read more

LeetCode – Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. Thoughts The key of this problem is using the right loop condition. And change what is necessary in each loop. You can use different iteration conditions like the following 2 … Read more

LeetCode – String to Integer (atoi) (Java)

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Analysis The following cases should be considered for this problem: 1. null or empty string 2. white spaces 3. +/- … Read more

LeetCode – 3Sum

Problem: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) … Read more

Yet Another “Java Passes By Reference or By Value”?

This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value. 1. Some Definitions Pass by value: make a copy in memory of the actual parameter’s value that is passed in. Pass by reference: pass a copy of … Read more

How to Build Your Own Java library?

Code reuse is one of the most important factors in software development. It is a VERY good idea to put frequently-used functions together and build a library for yourself. Whenever some method is used, just simply make a method invocation. For Java, it’s straightforward to manage such a library. Here a simple example in Eclipse. The library will contain only one “add” method for demo purpose.

Step 1: Create a “Java Project” named as “MyMath”, and a simple “add” method under “Simple” class.

Package structure is as follows:

Read more