import java.util.LinkedList;
public class Solution {
    public String ReverseSentence(String str) {
        if(str == null || str.length() < 2) {
            return str;
        }
        char[] arr = str.toCharArray();
        LinkedList<Integer> spaceList = new LinkedList<>();
        for(int i = 0; i < arr.length; i++) {
            if(arr[i] == ' ') {
                spaceList.addLast(i);
            }
        }
        if(spaceList.isEmpty()) {
            return str;
        }
        int pre = 0;
        while(!spaceList.isEmpty()) {
            reverse(arr, pre, spaceList.getFirst() - 1);
            pre = spaceList.getFirst() + 1;
            spaceList.removeFirst();
            if(spaceList.isEmpty()) {
                reverse(arr, pre, arr.length - 1);
            }
        }
        reverse(arr, 0, arr.length - 1);
        return new String(arr);
    }
    public void reverse(char[] arr, int l, int h) {
        while(l < h) {
            swap(arr, l, h);
            l++;
            h--;
        }
    }
    public void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}