NIHAO IX: the role of gas inflows and outflows in driving the contraction and expansion of cold dark matter haloes