IntList / IntListElt CS 313 Smalltalk linked list example Initial version (first two videos) Class IntListElt ================ Object subclass:#IntListElt instanceVariableNames:'val next' classVariableNames:'' poolDictionaries:'' category:'DanielsClasses' Class methods ------------- none (the accessor methods val: and next: will be used to initialize the instance variables) Instance methods ---------------- val: anInt "set the value of the instance variable 'val'" val := anInt val "return the value of the instance variable 'val'" ^ val next: anIntListElt "set the value of the instance variable 'next'" next := anIntListElt next "return the value of the instance variable 'next'" ^ next Class IntList ============= Object subclass:#IntList instanceVariableNames:'head' classVariableNames:'' poolDictionaries:'' category:'DanielsClasses' Class methods ------------- none ("new" will initialize "head" to nil, which is just what we want) Instance methods ---------------- isEmpty "returns whether list is empty" ^ (head == nil) first "returns first integer in the list" "assert: list not empty" self isEmpty ifTrue: [self error: 'cannot get first of empty list']. ^ head val add: anInt "inserts anInt at the head of the list" | e | e := IntListElt new. e val: anInt. e next: head. head := e remove "removes first element in the list and returns its value" "assert: list not empty" | v | self isEmpty ifTrue: [self error: 'cannot remove from empty list']. v := head val. head := head next. ^ v Initial testing and sample output ================================= Transcript clear. x := IntList new. Transcript show: 'isEmpty -> '; show: x isEmpty; cr. Transcript show: 'add: 3'; cr. x add: 3. Transcript show: 'isEmpty -> '; show: x isEmpty; cr. Transcript show: 'add: 2'; cr. x add: 2. Transcript show: 'add: 1'; cr. x add: 1. Transcript show: 'first -> '; show: x first; cr. Transcript show: 'remove -> '; show: x remove; cr. Transcript show: 'remove -> '; show: x remove; cr. Transcript show: 'remove -> '; show: x remove; cr. Transcript show: 'isEmpty -> '; show: x isEmpty; cr. output (produced using "doIt" on the code above): ------------------------------------------------- isEmpty -> true add: 3 isEmpty -> false add: 2 add: 1 first -> 1 remove -> 1 remove -> 2 remove -> 3 isEmpty -> true