When the Bitcoin client looks at the input of a transaction, it know the hash of the previous transaction from which the funds are coming, however then, how does it know that this output has not been spent already? Does it need to scan the whole blocklist for another transaction spending that same output? Isn't that very inefficient?
Bitcoin-Qt marks outputs as spent in the database once they are spent. To check whether an input's prev-out is spent, Bitcoin just needs to look up the transaction and check whether the output is marked spent.
Other ways of doing it are to have a set of all unspent outputs and check whether the prev-out is in this set (future versions of Bitcoin will do something like this), or to index inputs by their prev-outs.
It is similar to the question here
Suppose A, a peer, receives 'B' BTCs from various transactions: B1,B2,B3, etc. Also, A had spent 'S' BTCs in various transactions S1,S2,S3, etc. Now, whenever a new transaction is initiated from A to C (eg: A wants to transfer X bitcoins to C), the transaction has to be verified as follows.
- The full nodes have the UTXO (Unspent Transaction) details. The full nodes go through this UTXO database and verify if S1,S2,S3 are unspent or not. UTXO's size is around 512 MB. So, not difficult to go through all of the UTXO.
- Verification can also be done via SPV nodes, a lightweight client. These SPV nodes do not have the UTXO details. However, they have the header information of the entire blockchain. So, a new transaction is initiated, SPV client requests the full node to give information of the S1,S2,S3 transactions. Full node gives this information in the form of Merkel Trees. SPV node verifies the validity of these Merkel trees using the blockchain header info. The blockchain header would not change for all the transactions which are 'old enough'. As a conservative rule, people usually wait for at least 6 more blocks to be built on top of this present block, before delivering their goods or service.
Please refer to this link as well- Good article on how individual transactions are processed.