Solutions to other chapters:
Java Methods A & AB:
Object-Oriented Programming and Data Structures
Answers and Solutions to Exercises
Chapter 20
1. |
|
ListNode node3 = new ListNode("Node 3", null);
ListNode node2 = new ListNode("Node 2", node3);
ListNode node1 = new ListNode("Node 1", node2);
ListNode head = node1; |
3. |
|
public ListNode removeFirst(ListNode head)
{
if (head == null)
throw new NoSuchElementException();
ListNode temp = head.getNext();
head.setNext(null);
return temp;
} |
5. |
|
public ListNode add(ListNode head, Object value)
{
ListNode newNode = new ListNode(value, null);
if (head == null)
head = newNode;
else
{
ListNode node = head;
while (node.getNext() != null)
node = node.getNext();
node.setNext(newNode);
}
return head;
} |
9. |
|
public ListNode insertInOrder(ListNode head, String s)
{
ListNode node = head, prev = null;
while (node != null && s.compareTo(node.getValue()) > 0)
{
prev = node;
node = node.getNext();
}
if (node != null && s.equals(node.getValue()))
return head;
ListNode newNode = new ListNode(s, node);
if (prev == null)
head = newNode;
else
prev.setNext(newNode);
return head;
} |
|