Udemy: Master Coding Interview - Linked Lists - #9

Run Settings
LanguageC#
Language Version
Run Command
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); Console.WriteLine("New list: List = " + list.ToString()); list.Append(5); Console.WriteLine("Append(5): List = " + list.ToString()); list.Append(16); Console.WriteLine("Append(16): List = " + list.ToString()); list.Prepend(8); Console.WriteLine("Prepend(8): List = " + list.ToString()); list.Insert(6, 1); Console.WriteLine("Insert(6, 1): List = " + list.ToString()); list.Insert(7, 3); Console.WriteLine("Insert(7, 3): List = " + list.ToString()); list.Remove(0); Console.WriteLine("Remove(0): List = " + list.ToString()); list.Remove(1); Console.WriteLine("Remove(1): List = " + list.ToString()); list.Remove(3); Console.WriteLine("Remove(3): List = " + list.ToString()); list.Prepend(11); Console.WriteLine("Prepend(11): List = " + list.ToString()); list.Append(12); Console.WriteLine("Append(12): 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; break; } prev = current; current = current.next; count++; } } this.size++; } public void Remove(int index) { if (index == 0) { this.head = this.head.next; } else { Node current = this.head; Node prev = null; int count = 0; while (current != null) { if (count == index) { prev.next = current.next; break; } if (index == this.size - 1) { this.tail = current; } prev = current; current = current.next; count++; } } this.size--; } 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; } }
Editor Settings
Theme
Key bindings
Full width
Lines