using
System;
class
DoubleLinkedListNode
{
public
int
Val {
get
;
set
; }
public
DoubleLinkedListNode Next {
get
;
set
; }
public
DoubleLinkedListNode Prev {
get
;
set
; }
public
DoubleLinkedListNode(
int
val = 0,
DoubleLinkedListNode next =
null
,
DoubleLinkedListNode prev =
null
)
{
Val = val;
Next = next;
Prev = prev;
}
}
class
LRUCache
{
private
DoubleLinkedListNode head;
private
DoubleLinkedListNode tail;
private
DoubleLinkedListNode temp;
private
int
status;
public
LRUCache()
{
head =
null
;
tail =
null
;
temp =
null
;
status = 0;
}
public
int
AddNode(
int
value)
{
if
(head ==
null
)
{
head =
new
DoubleLinkedListNode(value);
tail = head;
head.Prev =
null
;
}
else
{
temp = tail;
tail.Next =
new
DoubleLinkedListNode(value);
tail = tail.Next;
tail.Prev = temp;
}
tail.Next =
null
;
return
0;
}
public
int
Display()
{
if
(head ==
null
)
{
Console.WriteLine(
"Add a node first"
);
return
-2;
}
else
{
temp = head;
string
str =
""
;
while
(temp !=
null
)
{
str += $
"[{temp.Val}]->"
;
temp = temp.Next;
}
Console.WriteLine(str +
"NULL"
);
}
return
0;
}
public
int
SearchCache(
int
value)
{
if
(head ==
null
)
{
Console.WriteLine(
"Add a node first"
);
return
-1;
}
temp = head;
while
(temp !=
null
)
{
if
(temp.Val == value)
{
while
(temp != head)
{
temp.Val = temp.Prev.Val;
temp = temp.Prev;
}
head.Val = value;
return
0;
}
temp = temp.Next;
}
temp = tail.Prev;
while
(temp !=
null
)
{
temp.Next.Val = temp.Val;
temp = temp.Prev;
}
head.Val = value;
return
0;
}
public
int
NumberOfNodes(
int
number)
{
for
(
int
i = 0; i < number; i++)
{
status = AddNode(0);
if
(status < 0)
{
Console.WriteLine(
"Could not assign node"
);
return
status;
}
}
return
0;
}
public
int
FreeCache()
{
temp = head;
while
(temp !=
null
)
{
head = head.Next;
temp = head;
}
tail =
null
;
return
0;
}
public
void
LRUOp(
int
[] arr,
int
n)
{
for
(
int
i = 0; i < n; i++)
{
status = SearchCache(arr[i]);
if
(status < 0)
{
Environment.Exit(1);
}
status = Display();
}
}
}
class
Program
{
static
void
Main(
string
[] args)
{
int
MEMSIZE = 5;
LRUCache cache =
new
LRUCache();
cache.NumberOfNodes(MEMSIZE);
int
n = 10;
int
[] arr = { 1, 2, 3, 4, 5, 2, 10, 7, 11, 1 };
cache.LRUOp(arr, n);
cache.FreeCache();
}
}