| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
About Exam
hard Solved by 1 students
Tracing Doubly Linked List Operations
< Prev
Next >

Consider the following DoublyLinkedList class. What is printed as a result of executing the main method?

public class DoublyLinkedList {
    class Node { 
       int val;
       Node prev, next;
       Node(int v) { val = v; }
    }
    
    Node head, tail;
    
    public void addAtHead(int v) {
      Node n = new Node(v);
      if(head == null) {
         head = tail = n;
      } else {
         n.next = head;
         head.prev = n;
         head = n;
      }
    }
    
    public void addAtTail(int v) {
      Node n = new Node(v);
      if(tail == null) {
         head = tail = n;
      } else {
         tail.next = n;
         n.prev = tail;
         tail = n;
      }
    }
    
    public void remove(int v) {
      Node current = head;
      while(current != null) {
         if(current.val == v) {
           if(current.prev != null) {
              current.prev.next = current.next;
           } else {
              head = current.next;
           }
           if(current.next != null) {
              current.next.prev = current.prev;
           } else {
              tail = current.prev;
           }
           break;
         }
         current = current.next;
      }
    }
    
    public void display() {
      Node current = head;
      while(current != null) {
         System.out.print(current.val + " ");
         current = current.next;
      }
      System.out.println();
    }
    
    public static void main(String[] args) {
       DoublyLinkedList dll = new DoublyLinkedList();
       dll.addAtHead(4);
       dll.addAtTail(8);
       dll.addAtHead(2);
       dll.addAtTail(10);
       dll.remove(8);
       dll.display();
    }
}
A

2 8 10

B

2 4 10

C

2 4 8

D

4 2 10

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy