Suppose we are implementing a stack using a singly linked list where the head of the list is treated as the top of the stack. Specify the correct implementation of push() method 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 ánLời giảiChọn phương án để mở
Đáp án đúng: "
void push(Object x) {
Node p = new Node(x);
p.next = head;
head=p;
}". Với danh sách liên kết đơn mà nút đầu là đỉnh ngăn xếp, phép đẩy phải làm đúng hai việc theo đúng thứ tự: cho nút mới trỏ sang đỉnh cũ bằng p.next = head, rồi dời chính đỉnh về nút mới bằng head = p; nhờ vậy toàn bộ phần dưới của ngăn xếp vẫn liền mạch. Bản "
void push(Object x) {
Node p = new Node(x);
p.next = head;
}" thiếu lệnh dời đỉnh, nên head vẫn chỉ vào nút cũ và nút vừa tạo không ai trỏ tới, ngăn xếp coi như không thay đổi. Bản "
void push(Object x) {
Node p = new Node(x);
p.next = null;
head=p;
}" cắt liên kết tới phần cũ: head chỉ vào nút mới nhưng nút mới trỏ vào null, nên mọi phần tử đã đẩy trước đó mất hết. Bản "
void push(Object x) {
Node p = new Node(x);
p.next = head;
head=p.next;
}" gán head bằng p.next, mà p.next vừa được đặt bằng head, nên head giữ nguyên giá trị cũ và nút mới bị bỏ rơi.
Cùng phần 2
Select the statement that is most correct.
Which of the following applications may not use a stack?Có lời giảiCâu hỏiConsider the following pseudocode:
declare a stack of characters
while(there are more characters in the word to read)
{read a character
if a character is '*' then
pop the stack
else
push the character into the stack
}
while(the stack is not empty)
pop and write the poped character to the screen
What is written to the screen for the input "Good**Morn**in***g" ?Có lời giảiCâu hỏiConsider the following pseudocode:
declare a stack of characters
while(there are more characters in the word to read)
{read a character
if a character is '*' then
pop and write the poped character to the screen
else
push the character into the stack
}
What is written to the screen for the input "Good**Morn**i***ng" ?Có lời giảiCâu hỏiCả 51 câu của chủ đề51 câu
Xuất hiện trong 1 bộ đề
Đi tiếp từ đây