Skip to content

Instantly share code, notes, and snippets.

// in this context, we've already know that the list has cycle
// suppose there is a class Node
// public class Node<Item>{
// Item item;
// Node next;
// }
// import the Node class here;
public class DetectCycleStartInList{// I wish I could use a better name :)
import java.util.Hashtable;
public class CloneDoubleLinkedList{
private class Node{
private String item;
private Node next;
private Node random;
}
public Node cloneListClever(Node first){
Node current = first;
import java.util.Stack;
public class SimplifyPath {
public String simplifyPath(String path) {
if(path == null) return null;
Stack<String> s = new Stack<String>();
int len = path.length();
StringBuilder b = new StringBuilder();
String item = null;
for (int i = 1; i < len; i++){ // start with the char at index 1 since the first is always '/'
char c = path.charAt(i);
import java.util.Stack;
import java.util.LinkedList;
public class SymmetricTree {
public boolean isSymmetricQueue(TreeNode root) {
if (root == null) return true; // if you say so
// initialize a queue since we are going to use breadth first traverse
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
if (root.left !=null && root.right != null) {
@jingz8804
jingz8804 / Evaluate.java
Created March 21, 2014 22:03
the Evaluate class in the book Algorithms 4th edition with slight modification
import java.util.Stack;
public class Evaluate{
private Stack<Double> operands;
private Stack<String> operators;
public Evaluate(){
operands = new Stack<Double>();
operators = new Stack<String>();
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
public class ZigZagConversion {
public String convert(String s, int nRows) {
// corner cases
if(s == null) return null;
if(s.equals("")) return s;
if(nRows == 0) return null;
if(nRows == 1) return s;
StringBuilder[] builders = new StringBuilder[nRows];
for(int i = 0; i < nRows; i++){
import java.util.ArrayList;
public class SpiralMatrix {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
if (matrix == null)
return null;
if (matrix.length == 0)
return new ArrayList<Integer>(); // ask first
int nrows = matrix.length;
int ncols = matrix[0].length;
public class SetMatrixZeros {
public void setZeroes(int[][] matrix) {
if(matrix == null) return;
if(matrix.length == 0) return;
int m = matrix.length;
int n = matrix[0].length;
boolean[] rows = new boolean[m];
boolean[] cols = new boolean[n];
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Stack;