using System;
class DoublyLinkedList {
public class Node {
public Node next;
public Node prev;
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!");
DoublyLinkedList list = new DoublyLinkedList(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 DoublyLinkedList(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;
item.prev = this.tail;
this.tail = item;
this.size++;
}
public void Prepend(int value) {
Node item = new Node(value);
item.next = this.head;
this.head.prev = item;
this.head = item;
this.size++;
}
public void Insert(int value, int index) {
Node current = this.head;
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 = current;
item.prev = current.prev;
current.prev.next = item;
current.prev = item;
break;
}
current = current.next;
count++;
}
}
this.size++;
}
public void Remove(int index) {
if (index == 0) {
this.head = this.head.next;
} else {
Node current = this.head;
int count = 0;
while (current != null) {
if (count == index) {
if (index == this.size - 1) {
this.tail = current.prev;
this.tail.next = null;
} else {
current.next.prev = current.prev;
current.prev.next = current.next;
}
break;
}
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;
}
}