Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DoubleLinkedList
- {
- class Program
- {
- static void Main(string[] args)
- {
- DoubleLinkedList myList = new DoubleLinkedList();
- myList.AddLast(2);
- myList.AddFirst(1);
- myList.AddFirst(0);
- myList[2] = 3;
- myList.Remove(3);
- DoubleLinkedList myList2 = new DoubleLinkedList(myList);
- Console.WriteLine(myList[1]);
- Console.ReadKey();
- }
- }
- class DoubleLinkedList
- {
- ListElement first = null;
- ListElement last = null;
- int count = 0;
- public int Count => count;
- public DoubleLinkedList()
- {
- first = last = null;
- }
- public DoubleLinkedList(DoubleLinkedList list)
- {
- ListElement tempCopy = list.first;
- while (tempCopy != null)
- {
- this.AddLast(tempCopy.value);
- if (tempCopy.next != null)
- tempCopy = tempCopy.next;
- else
- tempCopy = null;
- }
- }
- public int this[int index]
- {
- get
- {
- if (index < 0 || index >= count) throw new IndexOutOfRangeException();
- ListElement temp = first;
- int i = index;
- while(i-- > 0)
- temp = temp.next;
- return temp.value;
- }
- set
- {
- if (index < 0 || index >= count) throw new IndexOutOfRangeException();
- ListElement temp = first;
- int i = index;
- while (i-- > 0)
- temp = temp.next;
- temp.value = value;
- }
- }
- public void AddFirst(int value)
- {
- ListElement newElement = new ListElement(value);
- if (count == 0)
- {
- first = newElement;
- last = newElement;
- }
- else
- {
- newElement.next = first;
- first.prev = newElement;
- first = newElement;
- }
- count++;
- }
- public void AddLast(int value)
- {
- ListElement newElement = new ListElement(value);
- if (count == 0)
- {
- first = newElement;
- last = newElement;
- }
- else
- {
- newElement.prev = last;
- last.next = newElement;
- last = newElement;
- }
- count++;
- }
- public void Remove(int value)
- {
- if (count <= 0) throw new Exception("List is empty!");
- ListElement temp = first;
- for(int i = 0; i < count; i++)
- {
- if(temp.value == value)
- {
- if (i == 0)
- first = first.next;
- if (i == count - 1)
- last = last.prev;
- if (temp.next != null)
- {
- temp.next.prev = temp.prev;
- temp.prev.next = temp.next;
- }
- else
- temp.prev.next = null;
- temp = null;
- count--;
- return;
- }
- temp = temp.next;
- }
- }
- private class ListElement
- {
- public int value;
- public ListElement next = null;
- public ListElement prev = null;
- public ListElement(int Value, ListElement Next = null, ListElement Prev = null)
- {
- value = Value;
- next = Next;
- prev = Prev;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement