-
Notifications
You must be signed in to change notification settings - Fork 56
/
11.LinearTimeDataStructure.cs
85 lines (73 loc) · 1.61 KB
/
11.LinearTimeDataStructure.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//Design and implement a data structure
//in which Insert, Peek, Remove, Contains
//GetElement can be done in O(n) time
using System;
using System.Collections.Generic;
namespace LinearTimeDataStructure
{
public class myDS
{
private Dictionary<int,int> dictionary;
private List<int> list;
public myDS()
{
this.dictionary = new Dictionary<int, int> ();
this.list = new List<int> ();
}
public List<int> Peek()
{
return list;
}
public void Insert (int n)
{
list.Add (n);
int index = list.Count - 1;
dictionary.Add (n, index);
}
public void Remove (int n)
{
int index = dictionary[n];
int last = list [list.Count - 1];
list.RemoveAt (list.Count - 1);
list [index] = last;
dictionary [last] = index;
dictionary.Remove (n);
}
public bool Contains (int n)
{
return dictionary.ContainsKey (n);
}
public int GetRandomElement ()
{
Random rd = new Random ();
int number = rd.Next (list.Count);
return list [number];
}
public int GetElement(int index)
{
return list [index];
}
}
class MainClass
{
public static void Main (string[] args)
{
myDS myds = new myDS ();
myds.Insert (11);
myds.Insert (12);
myds.Insert (13);
myds.Insert (54);
myds.Remove (12);
List<int> testlist = myds.Peek ();
foreach (int i in testlist) {
Console.WriteLine (i);
}
bool b = myds.Contains (34);
Console.WriteLine (b);
Console.WriteLine (myds.GetRandomElement ());
Console.WriteLine (myds.GetRandomElement ());
Console.WriteLine (myds.GetRandomElement ());
Console.WriteLine (myds.GetRandomElement ());
}
}
}