Specify the correct implementation of pop() method of a stack of Integers. This stack uses java.util.LinkedList for storing data and the end of the list is treated as the top of the stack. (Choose the most suitable one)

4 phương ánCó giải thích

Các phương án trả lời

Chọn một phương án
Lời giảiChọn phương án để mở

Đáp án đúng: "Integer pop() {

Lời giải
if (isEmpty()) return(null);
return((Integer) pool.removeLast());

}". Cuối danh sách là đỉnh ngăn xếp, và java.util.LinkedList có sẵn removeLast() tháo nút cuối rồi trả về phần tử đó, đúng ngữ nghĩa pop là lấy ra và trả về; kiểu trả Integer cho phép trả null khi rỗng, còn phép ép sang Integer hợp với việc danh sách thô lưu Object. Vì vậy "

Lời giải
void pop(Integer x) {
  if (isEmpty()) return(null);
  pool.remove(pool.size()-1);
}

" sai vì hàm void không được return(null), lại nhận tham số và không trả gì nên phần tử đỉnh không bao giờ tới tay người gọi. "Integer pop() {

Lời giải
if (isEmpty()) return;
return((Integer) pool.remove(pool.size()-1));

}" sai vì hàm khai báo trả Integer mà có lệnh return trống, trình biên dịch báo thiếu giá trị trả về. "Integer pop() {

Lời giải
if (isEmpty()) return(null);
return((Integer) pool.remove(pool.size()));

}" sai vì chỉ số hợp lệ chỉ đến size()-1, nên remove(pool.size()) luôn vượt biên và ném IndexOutOfBoundsException.

Cùng phần 2

Xuất hiện trong 1 bộ đề