Java Reference
In-Depth Information
System.out.printf("\nThe items in the list are\n");
printList(top);
} //end main
public static void printList(Node top) {
while (top != null) { //as long as there's a node
System.out.printf("%d ", top.num);
top = top.next; //go on to the next node
}
System.out.printf("\n");
} //end printList
} //end class BuildList2
class Node {
int num;
Node next;
public Node(int n) {
num = n;
next = null;
}
} //end class Node
The following is a sample run of Program P3.2:
Enter some integers ending with 0
9 1 8 2 7 3 6 4 5 0
The items in the list are
5 4 6 3 7 2 8 1 9
Program P3.1 inserts incoming numbers at the tail of the list. This is an example of adding an item to a queue. A
queue is a linear list in which insertions occur at one end and deletions (see the next section) occur at the other end.
Program P3.2 inserts incoming numbers at the head of the list. This is an example of adding an item to a stack.
A stack is a linear list in which insertions and deletions occur at the same end . In stack terminology, when we add an
item, we say the item is pushed onto the stack. Deleting an item from a stack is referred to as popping the stack.
We will treat with stacks and queues more fully in Chapter 4.
3.6 Deletion from a Linked List
Deleting a node from the top of a linked list is accomplished by this statement:
top = top.next;
This says let top point to whatever the first node was pointing at (that is, the second node, if any). Since top is now
pointing at the second node, effectively the first node has been deleted from the list. The statement changes the following:
top
23
52
15
 
 
Search WWH ::




Custom Search