Quick actions

cmd+k|ctrl+k

Navigation

Languages

Udemy: Master Coding Interview - Stacks + Queues - #118

Snippet info

Language

Csharp

Visibility

public

Author

jcurrie33

Created

2020-08-10T04:33:14Z

Updated

2020-08-10T04:33:52Z

using System;

public class Node {
    public Node next;
    public string value;
    public Node(string value) {
        this.value = value;
    }
}

class Queue {
    Node first;
    Node last;
    int length = 0;
    
    static void Main() {
        Console.WriteLine("Hello World!");
        Queue q = new Queue();
        Console.WriteLine("q: " + q.ToString());
        q.Enqueue("a");
        Console.WriteLine("q: " + q.ToString());
        q.Enqueue("b");
        Console.WriteLine("q: " + q.ToString());
        q.Enqueue("c");
        Console.WriteLine("q: " + q.ToString());
        q.Dequeue();
        Console.WriteLine("q: " + q.ToString());
        q.Dequeue();
        Console.WriteLine("q: " + q.ToString());
        q.Dequeue();
        Console.WriteLine("q: " + q.ToString());
    }
    
    public void Enqueue(string value) {
        Node item = new Node(value);
        if (this.length == 0) {
            this.first = item;
        } else {
            this.last.next = item;
        }
        this.last = item;
        
        this.length++;
    }
    
    public string Dequeue() {
        if (this.first != null) {
            string value = this.first.value;
            this.first = this.first.next;
            this.length--;
            return value;
        }
        return null;
    }
    
    public string Peek() {
        if (this.first != null) {
            return this.first.value;
        }
        return null;
    }
    
    public bool IsEmpty() {
        return this.length == 0;
    }
    
    public string ToString() {
        string s = "{";
        Node current = this.first;
        int count = 0;
        while (current != null) {
            if (count > 0) {
                s += ", ";
            }
            s += "" + current.value;
            current = current.next;
            count++;
        }
        s += "}";
        return s;
    }
}
INFO