C Sc 227 11-April Pracitce Quiz

Total Page:16

File Type:pdf, Size:1020Kb

C Sc 227 11-April Pracitce Quiz

Section Linked Structures

Use this singly-linked structure to answer questions 1-4

front

"A" "B" "C"

1. What is the value of front.data? ______2. What is the value of front.next.next.data? ______3. What is the value of front.next.data? ___ 4. What is the value of front.next.next.next? ______5. Write the code that will generate the following linked structure.

front back

"1st" "2nd"

6. Draw a picture of the linked structure built from this code: Node n1 = new Node("aaa"); n1.next = new Node("bbb"); n1.next.next = new Node("ccc"); n1.next.next.data = "fff";

7. Using the code in question 6, What happens with this code n1.next.next.next.data = "ggg";

8. Complete methods toString addLast as if it was in the LinkedList class began in lecture so it adds a new element at the end of a linked structure referred to by front. The following code should generate this picture of memory. LinkedList list = new LinkedList(); list.addLast("First"); list.addLast("Second");

list.addLast("Third"); front public class LinkList { "First" "Second" "Third" private class Node { private E data; private Node next;

public Node(E objectReference) { data = objectReference; }

public Node(E objectReference, Node nextReference) { data = objectReference; next = nextReference; } }

private Node front; private int n;

public LinkList() { front = null; n = 0; }

public void addFirst(E element) { front = new Node(element, front); n++; }

public void addLast(String element) {

ANSWERS

1. What is the value of front.data? __"A"____ 2. What is the value of front.next.next.data? __"C"____ 3. What is the value of front.next.data? _"B"__

4. What is the value of front.next.next.next? _null_____ 5. Write the code that will generate the following linked structure.

Node front = new Node("1st"); Node back = new Node("2nd"); front.next = back;

6. Draw a picture of the linked structure built from this code: Node n1 = new Node("aaa"); n1.next = new Node("bbb"); n1.next.next = new Node("ccc"); n1.next.next.data = "fff";

n1

"aaa" "bbb" "fff"

7. Null pointer exception

8. public void addLast(E element) { if (isEmpty()) this.addFirst(element); else { Node ref = front; while (ref.next != null) ref = ref.next; ref.next = new Node(element); } size++; }

Recommended publications