Tutorial 10 Lecturer: Steve Bellantoni Tutor: Andria Hunter =========== 981130 @10am (RW229) @1pm (EM108) CSC108, Fall 1998 Tutorial notes, T10 ================================================================== Topics ------ - A4 questions, explain each method - How to implement A4 using arrays How to Implement A4 Using Arrays -------------------------------- (1) Simple method where the top of the stack is the last element in the array. public class LinkedStack { private Object[] elements; private int elementCount; public LinkedStack (int maxSize) { elements = new Object [maxSize]; elementCount = 0; } public void push (Object data) { elements[elementCount] = data; elementCount++; } public Object pop () { elementCount--; return elements[elementCount]; } } (2) Harder method where the top of the stack is the first element (index 0) in the array. public class LinkedStack { private Object[] elements; private int elementCount; public LinkedStack (int maxSize) { elements = new Object [maxSize]; elementCount = 0; } public void push (Object data) { // must shift the other elements to the right, to make // room for new element which will be inserted at index 0. for (int i=elementCount-1; i >= 0; i--) elements[i+1] = elements[i]; elements[0] = data; elementCount++; } public Object pop () { // save a reference to object to be returned Object tempObject = element[0]; // must shift the other elements to the left, and // return the element at index 0. for (int i=1; i < elementCount; i++) elements[i-1] = elements[i]; elementCount--; return tempObject; } } Modify A1 to use Arrays ----------------------- public class ApplicationCentre { private Student[] students; private int studentCount; private static final int NOTFOUND = -1; // Constructor public ApplicationCentre (int maxSize) { students = new Student [maxSize]; studentCount = 0; } // Add new student to application centre public boolean addStudent (Student newStudent) { if (studentCount < students.length) { students[studentCount] = newStudent; studentCount++; return true; } return false; } // Find the index of a student in the array public int findStudent (String name) { for (int i=0; i