Difference between revisions of "CSC212 Lab 6 Solutions 2014"
Line 2: | Line 2: | ||
---- | ---- | ||
<br /> | <br /> | ||
− | |||
=Problem 2= | =Problem 2= | ||
<br /> | <br /> | ||
Line 101: | Line 100: | ||
</source> | </source> | ||
<br /> | <br /> | ||
+ | <onlydft> | ||
+ | |||
=Problem 3= | =Problem 3= | ||
<br /> | <br /> |
Revision as of 16:46, 2 October 2014
--D. Thiebaut (talk) 13:04, 1 October 2014 (EDT)
Problem 2
class IntSLLNode {
public int info;
public IntSLLNode next;
public IntSLLNode( int el ) { this( el, null ); }
public IntSLLNode( int el, IntSLLNode n ) { info = el; next = n; }
}
public class MyLinkedList {
IntSLLNode head, tail;
int length;
public MyLinkedList() {
head = tail = null;
length = 0;
}
public boolean isEmpty() {
return head == null;
}
public void addToHead( int el ) {
head = new IntSLLNode( el, head );
if ( tail==null )
tail = head;
length++;
}
public void addToTail( int el ) {
if ( tail == null )
addToHead( el );
else {
tail.next = new IntSLLNode( el );
tail = tail.next;
length++;
}
}
public void printAll() {
for ( IntSLLNode it=head; it != null; it = it.next )
System.out.print( it.info + " " );
System.out.println( );
}
public int deleteFromHead() {
int el = head.info;
if ( tail==head )
head = tail = null;
else
head = head.next;
length--;
return el;
}
public void printStatus( String caption ) {
System.out.println( "+===========================================\n|" + caption );
System.out.println( "+===========================================\n| List:");
System.out.println( isEmpty()? "| is empty": "| is not empty" );
System.out.println( "| contains " + length + " element" + ((length!=1)? "s":"" ) );
System.out.print( "| elements: " );
printAll();
System.out.println( "+===========================================" );
}
public static void main(String[] args) {
MyLinkedList L = new MyLinkedList();
L.printStatus( "Brand new list" );
for ( int i=10; i<50; i+= 10 )
L.addToTail( i );
L.printStatus( "After adding 10, 20, ... to tail...");
L = new MyLinkedList();
L.printStatus( "Brand new list" );
for ( int i=5; i<50; i+= 10 )
L.addToHead( i );
L.printStatus( "After adding 5, 15, ... to head...");
while ( ! L.isEmpty() ) {
int el = L.deleteFromHead();
L.printStatus( "After removing " + el );
}
}
}