Deque
Anonymous contributor
Published Oct 2, 2024
Contribute to Docs
A deque is a data structure that allows elements to be added or removed from both ends, making it more versatile than a traditional queue or stack. In C#
there is no build-in deque
but it can be impleted using LinkedList
and List
classes C#
.
Implementing using LinkedList Class
LinkedList<T> deque = new LinkedList<T>();
T
: Specifies the element type.
Example 1
The below example shows how to implement deque using LinkedList
.
using System;using System.Collections.Generic;class Program {static void Main() {LinkedList<int> deque = new LinkedList<int>();// Adding elements to the frontdeque.AddFirst(1);deque.AddFirst(2);// Adding elements to the backdeque.AddLast(3);deque.AddLast(4);// Removing elements from the frontint front = deque.First.Value;deque.RemoveFirst();// Removing elements from the backint back = deque.Last.Value;deque.RemoveLast();foreach (int value in deque) {Console.WriteLine(value);}}}
Output:
13
Implementing using List Class
List<T> deque = new List<T>();
T
: Specifies the element type.
Example 2
The below example shows how to implement deque using List
.
using System;using System.Collections.Generic;class Program {static void Main() {List<int> deque = new List<int>();// Adding elements to the frontdeque.Insert(0, 1);deque.Insert(0, 2);// Adding elements to the backdeque.Add(3);deque.Add(4);// Removing elements from the frontint front = deque[0];deque.RemoveAt(0);// Removing elements from the backint back = deque[deque.Count - 1];deque.RemoveAt(deque.Count - 1);foreach (int value in deque) {Console.WriteLine(value);}}}
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.