Keep in mind, though, that there is a difference between what the regular chain of command is and who is given command in any particular instance.Trying to figure out the absolute chain-of-command is a lot like trying to figure out a meaningful and accurate formula for "stardates" that fit all its citations ... you can't.
Generally, Scotty was the goto third in command but not always. Sometimes it was given to Sulu. Sometimes a rarely seen Lt. DeSalle. It was even worse in The Next Generation.
The chain of command would determine who has authority over who in normal circumstances. So, for example, Data has authority over LaForge because Data is the second officer, even though Data and LaForge have the same rank.
The chain of command also determines who automatically takes command in an unexpected situation. So if Picard is killed or incapacitated, Riker takes command. If Riker is out of the game, Data takes command, etc.
However, when all is functioning normally and the captain leaves the bridge, he can assign command to whomever he wishes, without regard to the normal chain of command. So Kirk can give command to DeSalle or Picard can give it to Crusher or Sisko can give it to Ensign Ricky.