Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ControlFlow {
- public static void main(String[] args) {
- /* Creates a list of one Interger, namely 10 */
- SLList L = new SLList();
- L.addLast(20);
- L.addFirst(23);
- L.addFirst(12);
- L.displayList();
- }
- }
- public class SLList {
- public static class IntNode {
- public int item;
- public IntNode next;
- public IntNode(int i, IntNode n) {
- item = i;
- next = n;
- }
- public void displayNode(){
- System.out.println("{ "+ item + " } ");
- }
- }
- private IntNode sentinel;
- private int size;
- public SLList() {
- sentinel = new IntNode(63,null);
- size = 0;
- }
- public SLList(int x) {
- sentinel = new IntNode(63,null);
- sentinel.next = new IntNode(x,null);
- size += 1;
- }
- /**
- * Adds an item to the front of the list.
- */
- public void addFirst(int x) {
- sentinel.next=new IntNode(x,sentinel.next);
- size += 1;
- }
- /**
- * Retrieves the front item from the list.
- */
- public int getFirst() {
- return sentinel.next.item;
- }
- /**
- * Adds an item to the end of the list.
- */
- public void addLast(int x) {
- size += 1;
- IntNode p = sentinel;
- while (p.next != null) {
- p = p.next;
- }
- p.next = new IntNode(x, null);
- }
- public int size3() {
- return size;
- }
- /**
- * Returns the number of items in the list using recursion.
- */
- public int size() {
- IntNode p = sentinel;
- int count = 1;
- while (p.next != null) {
- p = p.next;
- count++;
- }
- return count;
- }
- public static int size2(IntNode p) {
- if (p.next == null) {
- return 1;
- }
- return 1 + size2(p.next);
- }
- public int size2() {
- return size2(sentinel);
- }
- public void displayList(){
- System.out.println("List (first --> last) ");
- IntNode current = sentinel;
- while(current != null){
- current.displayNode();
- current = current.next;
- }
- System.out.println();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement