Quick actions

cmd+k|ctrl+k

Navigation

Languages

Udemy: Master Coing Interview - Hash Tables - #96

Snippet info

Language

Csharp

Visibility

public

Author

jcurrie33

Created

2020-08-08T05:17:00Z

Updated

2020-08-08T05:17:00Z

using System;

class LinkedList {
    public class Node {
        public Node next;
        public int value;
        
        public Node(int value) {
            this.value = value;
        }
    }
    
    public Node head;
    public Node tail;
    int size = 0;
    
    static void Main() {
        Console.WriteLine("Hello World!");
        
        LinkedList list = new LinkedList(10);
        list.Append(5);
        list.Append(16);
        list.Prepend(8);
        list.Insert(6, 1);
        list.Insert(7, 3);
        Console.WriteLine("List = " + list.ToString());
    }
    
    public LinkedList(int value) {
        this.head = new Node(value);
        this.tail = this.head;
        this.size = 1;
    }
    
    public void Append(int value) {
        Node item = new Node(value);
        this.tail.next = item;
        this.tail = item;
        this.size++;
    }
    
    public void Prepend(int value) {
        Node item = new Node(value);
        item.next = this.head;
        this.head = item;
        this.size++;
    }
    
    public void Insert(int value, int index) {
        Node current = this.head;
        Node prev = null;
        if (index == 0) {
            Prepend(value);
        } else if (index == this.size) {
            Append(value);
        } else {
            int count = 0;
            while (current != null) {
                if (count == index) {
                    Node item = new Node(value);
                    item.next = prev.next;
                    prev.next = item;
                }
                prev = current;
                current = current.next;
                count++;
            }
        }
    }
    
    public string ToString() {
        string s = "{";
        Node current = this.head;
        int count = 0;
        while (current != null) {
            if (count > 0) {
                s += ", ";
            }
            s += "" + current.value;
            current = current.next;
            count++;
        }
        s += "}";
        return s;
    }
}
INFO