How would I go about counting backwards in a simple directed graph? - c#

So I have this graph with books I'm iterating through and printing them out.
public class Books : IBookFinder
{
private Books(Books next, string book)
{
Next = next;
Book = book;
}
public Books Next { get; }
public string Book { get; }
public Books Previous(string book)
{
return new Books(this, book);
}
public static Books Create(string book)
{
return new Books(null, book);
}
public string FromLeft(Books books, int numberFromLeft)
{
for (int i = 1; i < numberFromRight; i++)
{
books = books?.Next; //Go through the books and return null if books is null.
}
return books.book; //Should probably check for null here as it crashes if the input number is out of book range (something else than 1-4)
}
public string FromRight(Books books, int numberFromRight
{
//How to implement this bad boy?
}
}
All is well and good, but I want to implement a method FromRight so that I can write out the name of the book from it's placement in the graph, given a number input. For example, if inputting "3", it should output "Lord of the Rings". How would I go about doing that? Any hints greatly appreciated.
class Program
{
static void Main(string[] args)
{
var curr = Books
.Create("Harry Potter")
.Previous("Lord of the Rings")
.Previous("Twilight")
.Previous("Da Vinci Code");
while (curr != null)
{
if (curr.Next != null)
{
Console.Write(curr.Book + " --- ");
}
else
{
Console.WriteLine(curr.Book);
}
curr = curr.Next;
}
Console.WriteLine("Input number to pick a book");
var bookNumber = Console.ReadLine();
int n;
if (int.TryParse(bookNumber, out n)) //Checking if the input is a #
{
}
else
{
Console.WriteLine("Input was not a number!");
}
Console.WriteLine(bookNumber);
Console.ReadLine();
}
}
UPDATE:
I've managed to figure out a way to do it, without having to make a doubly linked list, even though that is of course probably the optimal solution for this problem.
I've made a helper function Count(), which takes the list and counts entries:
private int Count(Books books)
{
int count = 1;
while (books.Next != null)
{
books = books.Next;
count++;
}
return count;
}
I then use the return value of this method to select books from the right:
public string FromRight(Books books, int numberFromRight)
{
var bookCount = Count(books); //Getting the amount of books.
for (int i = numberFromRight; i < bookCount; i++)
{
books = boos?.Next;
}
return books.Book;
}

Since you are creating this like a linked list, to go backwards you need to create a doubly linked list: https://en.wikipedia.org/wiki/Doubly_linked_list
Your current code has no representation of the previous node. Set the previous node as that of the current while creating the next, then its iterating is just like you did originally.
Iterate until there is no Next, then print until there is no previous.

A single-linked list can only be iterated in a single direction, so it’s not possible to go backwards.
To get the nth element from the left, you simply need to go next n times. But to figure out elements from the right, you first need to get to the end. So to get the last element, you need to go next as often as possible. To get the next to last element, you need to go to the end and return the element before that.
You may see where this is going: In order to get the nth element from the right, you need to remember the last n elements while iterating through the linked list. This also means that in the worst case, you remember every item when getting the first element from the left—but from the right.
Implementing this is not too difficult, you can do this very easily with a list of length numberFromRight but since you are inserting at the end and removing elements from the beginning you would be shifting elements all the time. So you better use a fixed-length queue. Or you use a array with a variable pointer which avoids having to shift anything. A FromRight method could look like this:
public Element FromRight(int numberFromRight)
{
// increment the offset by one, so that `0` means the last element,
// and `1` means the one before last, etc.
numberFromRight++;
// create an array with `numberFromRight` slots
Element[] arr = new Element[numberFromRight];
// add the current item to the array
arr[0] = this;
// `i` is the index where to add the next element
int i = 1 % numberFromRight;
// iterate through all elements until the very end
Element current = this;
while (current.Next != null)
{
current = current.Next;
// add the current element to the array
arr[i] = current;
// increment the index by one, overflowing back to the beginning of the array
i = (i + 1) % numberFromRight;
}
// the element at position `i` is the nth element from the right.
return arr[i];
}
(I’ve chosen to implement this without your Books type since you mixed Books and Customers in a confusing way and I didn’t get that. This works for arbitrary linked lists.)
If you find yourself accessing elements from the end more regularly, you should consider using a doubly linked list instead which also maintains a pointer to the left element. This means that more references need be be maintained (increasing the complexity for list operations a bit) but results in a way better performance (since iterating from the end is the same as iterating from the beginning).
In general, you should always choose a data structure that fits your access pattern. No data structure is perfect for everything, so it’s important to understand the differences and to know what you really need in your application so you can choose well.

Related

Making a simple change function for a database app C#

Sorry if this is an ultra beginner question but, I need to be able to change all field values except the item number by giving its item number not array index. I already have a add and delete feature.
using System;
struct ItemData
{
public int ItemNumber;
public string Description;
public double PricePerItem;
public int QuantityOnHand;
public double OurCostPerItem;
public double ValueOfItem;
}
class Program
{
public static void Main()
{
int invItems = 0;
var items = new ItemData[10];
while (true)
{
Console.Write("1. Add, 2. Change, 3. Delete, 4. List:");
string strx = Console.ReadLine();
var choice = int.Parse(strx);
Console.WriteLine();
switch (choice)
{
This is what I have so far but not sure where to start
case 2: //change items
{
Console.Write("Please enter an item ID No:");
string input = Console.ReadLine();
int changeItemNumber = int.Parse(input);
bool foundItem = false;
for (int x = 0; x < invItems; x++)
{
if (items[x].ItemNumber == changeItemNumber)
{
//code
}
}
if (!foundItem)
{
Console.WriteLine("Item {0} not found", changeItemNumber);
}
break;
}
It's still a little unclear what you're asking so if this is wide of the mark then feel free to let me know.
Start by mapping out the flow of the process and then implement one piece at a time. Here's a basic series of operations you'll want to do, not necessarily in this order:
Input ItemNumber.
Find index of matching record in array.
If not found report error and stop.
Get record from user.
Set ItemNumber in record to entered value.
Store record in array at same index as original.
If you think about the way the rest of the program works you should see that some of those parts - maybe most of them - are already done somewhere in your code. Your add operation probably already has the Get record from user code. Your delete operation probably has Input ItemNumber and Find index of matching record in array done already.
So pull those parts out into methods and reuse them where it makes sense. Anywhere you're writing the same code multiple times with minor changes try to see if you can extract the code into a small method you can call with maybe some parameters. Your "input a number" code for instance - used for operation selection, item number entry and presumably whatever you're doing for delete - can be pulled out to a supporting method like this one:
static int InputNumber(string prompt)
{
Console.Write($"{prompt}: ");
var inputText = Console.ReadLine();
return int.Parse(inputText);
}
Now when you want to change the way you're doing number input you have a central place to make the changes and you don't have to worry about tracking down all the places you wrote the same code.
The same goes for the rest of the pieces. When two operations share some of the same code then pull that code out to supporting methods. Finding the index of an item in the array by some criteria can - and should - be one of those:
// Return array index of matching item or -1 if not found
int ItemIndex(int itemNumber)
{
for (int i = 0; i < invItems; i++)
{
if (items[i].ItemNumber == itemNumber)
return i;
}
return -1;
}
Likewise the code - whatever that looks like - that your add operation uses to get a record from the user.
Once you do that your change item case looks a lot simpler:
case 2: // change items
var itemNumber = InputNumber("Please enter an item ID");
var index = ItemIndex(itemNumber);
if (index == -1)
{
Console.WriteLine($"Item {itemNumber} not found.");
}
else
{
var newItem = InputItemData();
newItem.ItemNumber = itemNumber;
items[index] = newItem;
}
break;
For bonus points you can actually provide the current values to the InputItemData method so the user can re-use them instead of just asking for a complete new record each time.

C# - Accessing Lists from another Class or copying it? - Performance & Best Practice

I have a general question, concerning performance and best practice.
When working with a List (or any other datatype) from a different Class, which is better practice? Copying it at the beginning, working with the local and then re-copying it to the original, or always access the original?
An Example:
access the original:
public class A
{
public static List<int> list = new List<int>();
}
public class B
{
public static void insertString(int i)
{
// insert at right place
int count = A.list.Count;
if (count == 0)
{
A.list.Add(i);
}
else
{
for (int j = 0; j < count; j++)
{
if (A.list[j] >= i)
{
A.list.Insert(j, i);
break;
}
if (j == count - 1)
{
A.list.Add(i);
}
}
}
}
}
As you see I access the original List A.list several times. Here the alternative:
Copying:
public class A
{
public static List<int> list = new List<int>();
}
public class B
{
public static void insertString(int i)
{
List<int> localList = A.list;
// insert at right place
int count = localList.Count;
if (count == 0)
{
localList.Add(i);
}
else
{
for (int j = 0; j < count; j++)
{
if (localList[j] >= i)
{
localList.Insert(j, i);
break;
}
if (j == count - 1)
{
localList.Add(i);
}
}
}
A.list = localList;
}
}
Here I access the the list in the other class only twice (getting it at the beginning and setting it at the end). Which would be better.
Please note that this is a general question and that the algorithm is only an example.
I won't bother thinking about performance here and instead focus on best practice:
Giving out the whole List violates encapsulation. B can modify the List and all its elements without A noticing (This is not a problem if A never uses the List itself but then A wouldn't even need to store it).
A simple example: A creates the List and immediately adds one element. Subsequently, A never bothers to check List.Count, because it knows that the List cannot be empty. Now B comes along and empties the List...
So any time B is changed, you need to also check A to see if all the assumptions of A are still correct. This is enough of a headache if you have full control over the code. If another programmer uses your class A, he may do something unexpected with the List and never check if that's ok.
Solution(s):
If B only needs to iterate over the elements, write an IEnumerable accessor. If B mustn't modify the elements, make the accessor deliver copies.
If B needs to modify the List (add/remove elements), either give B a copy of the List (containing copies of the elements if they needn't be modified) and accept a new List from B or use an accessor as before and implement the necessary List operations. In both cases, A will know if B modifies the List and can react accordingly.
Example:
class A
{
private List<ItemType> internalList;
public IEnumerable<ItemType> Items()
{
foreach (var item in internalList)
yield return item;
// or maybe item.Copy();
// new ItemType(item);
// depending on ItemType
}
public RemoveFromList(ItemType toRemove)
{
internalList.Remove(toRemove);
// do other things necessary to keep A in a consistent state
}
}

C# data structure, list which can dynamically resize up to a given limit, and allows fast access to any index

I'm implementing a memory system for an AI agent. It needs to have an internal list of state transitions which is capped at some number, say 10000.
If at capacity, adding a new memory should automatically remove the oldest memory.
Importantly, I should also need to be able to quickly access any item in this list.
A wrapper for Queue at first seemed obvious, but Queue does not allow fast access of any element. (O(n))
Similarly, remove an item from the beginning of a List structure takes O(n).
LinkedLists allow fast additions and removals, but again do not allow quick access to every index.
An array would allow random access but obviously it's not dynamically resizeable and deletion is problematic.
I've seen a HashMap being suggested but I'm ensure how that might be implemented.
Suggestions?
If you want the queue to be a fixed length, you could use a circular buffer which enables O(1) enqueue, dequeue and indexing operations and automatically overwrites old entries when the queue is full.
Try using a Dictionary with a LinkedList. The keys of the Dictionary are the indexes of the LinkedList nodes and the values of the Dictionary are of type LinkedListNode; that is, the LinkedList nodes.
The Dictionary would give you almost an O(1) on its operations and removing/adding LinkedListNode(s) to the beginning or end of a LinkedList is of O(1) as well.
Another alternative is to use a HashTable. However, in this case you have to know the capacity of the table beforehand (See Hashtable.Add Method) in order to get the O(1) performance:
If Count is less than the capacity of the Hashtable, this method is an O(1) operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.
In the first solution, no matter what's the capcity of the LinkedList or the Dictionary you would still get almost an O(1) from both the Dictionary and the LinkedList. Of course that's going to be an O(3) or O(4) depending on the total number of operations that you perform on both the Dictionary and the LinkedList to do an add or remove operation inside your memory class. The search access is going to be always an O(1) because you will be using the Dictionary only.
HashMap is for Java, so the closest equivalent is Dictionary. C# Java HashMap equivalent. But I wouldn't say that this is the ultimate answer.
If you implement it as Dictionary, which key == the content, then you can search the content with O(1). However, you cannot have same key. Also, because it is not ordered, you may not know which the 1st content is.
If you implement it as Dictionary, which key == index, and value == the content, searching for the content still takes O(n) because you don't know the location of content.
A List or an Array will cost O(1) if you search the content by index reference. So, please double check your statement that it takes O(n)
If you search by index is sufficient, then circular array/ buffer which #Lee mentioned is good enough.
Otherwise, similar to DB, you might want to maintain in 2 separate data: 1 for storing the data (Circular Array) and the other one for search (Hash).
EDIT: #Lee has it right. A circular buffer seems to give you what you want. Answer left in place though.
I think the data structure you want might be a priority queue -- it depends on what you mean by 'quickly access any item'. If you mean 'able to enumerate all items in O(N)', then a priority queue fits the bill. If you mean 'enumerate the list in historical order', then it won't.
Assuming you need these operations;
add an item and associate with a time
remove the oldest item
enumerate all existing items in arbitrary order
Then you could easily extend this priority queue implementation I wrote a little while ago.
You'll want implement IEnumerable as a loop through the T[] data array from 0 to cursor. This will give you your enumeration.
Implement a GetItem(i) function which returns this.data[i] so long as i <= cursor.
Implement an automatic size limit by putting this into the Push() method;
if (queue.Size => 10000) {
queue.Pop();
}
I think this is O(ln n) for push and pop, and O(N) to enumerate ALL items, or O(i) to find ANY item, so long as you don't need them in order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mindfire.DataStructures
{
public class PiorityQueue<T>
{
private int[] priorities;
private T[] data;
private int cursor;
private int capacity;
public int Size
{
get
{
return cursor+1;
}
}
public PiorityQueue(int capacity)
{
this.cursor = -1;
this.capacity = capacity;
this.priorities = new int[this.capacity];
this.data = new T[this.capacity];
}
public T Pop()
{
if (this.Size == 0)
{
throw new InvalidOperationException($"The {this.GetType().Name} is Empty");
}
var result = this.data[0];
this.data[0] = this.data[cursor];
this.priorities[0] = this.priorities[cursor];
this.cursor--;
var loc = 0;
while (true)
{
var l = loc * 2;
var r = loc * 2 + 1;
var leftIsBigger = l <= cursor && this.priorities[loc] < this.priorities[l];
var rightIsBigger = r <= cursor && this.priorities[loc] < this.priorities[r];
if (leftIsBigger)
{
Swap(loc, l);
loc = l;
}
else if (rightIsBigger)
{
Swap(loc, r);
loc = r;
}
else
{
break;
}
}
return result;
}
public void Push(int priority, T v)
{
this.cursor++;
if (this.cursor == this.capacity)
{
Resize(this.capacity * 2);
};
this.data[this.cursor] = v;
this.priorities[this.cursor] = priority;
var loc = (this.cursor -1)/ 2;
while (this.priorities[loc] < this.priorities[cursor])
{
// swap
this.Swap(loc, cursor);
}
}
private void Swap(int a, int b)
{
if (a == b) { return; }
var data = this.data[b];
var priority = this.priorities[b];
this.data[b] = this.data[a];
this.priorities[b] = this.priorities[a];
this.priorities[a] = priority;
this.data[a] = data;
}
private void Resize(int newCapacity)
{
var newPriorities = new int[newCapacity];
var newData = new T[newCapacity];
this.priorities.CopyTo(newPriorities, 0);
this.data.CopyTo(newData, 0);
this.data = newData;
this.priorities = newPriorities;
this.capacity = newCapacity;
}
public PiorityQueue() : this(1)
{
}
public T Peek()
{
if (this.cursor > 0)
{
return this.data[0];
}
else
{
return default(T);
}
}
public void Push(T item, int priority)
{
}
}
}

Bubblesort implementation using linked-list only partially works

I am trying to use bubble sort to sort a list of items. I am aware that this is not the most effective method of sorting; however, I require this method to work before moving on to better things. My current code partially sorts a list, but I cannot see what I am doing wrong.
public class ListComponents
{
public int Priority;
public string Name;
public ListComponents Next;
}
public void bubblesort()
{
ListComponents Current = Head;
int temp = 0;
bool swapped = true;
while (swapped)
{
Print(); // Debug Function to print each swap
Current = Head.Next; // RESET CURRENT TO HEAD + 1 ON EACH ITERATION?
swapped = false;
for (int sort = 0; sort < (size - 1); sort++) //Size defined as # of items in list
{
if (Current != null &&
Current.Next != null &&
Current.Priority> Current.Next.Priority)
{
temp = Current.Priority;
Current.Priority= Current.Next.Priority;
Current.Next.Priority= temp;
Current = Head; // POTENTIAL ISSUE?
swapped = true;
}
}
}
}
My debug print function shows the following, showing how the values are almost in order:
List: 4 2 1 3 (Inital List Order)
List: 1 4 2 3 (First Swap)
List: 1 2 4 3 (Second Swap)
The issue seems to be with setting the 'Current' value, although I cannot see where this is not working.
My advice: start over. This is a mess.
Here's how I would tackle problems like this when I was a beginner. Start by writing the code in pseduo-code:
void BubbleSort(ListComponent head)
{
if the list is of zero length then it is already sorted, so return
if the list is of length one then it is already sorted, so return
Otherwise, the list is of length two or more. Therefore we know that
a first item exists and a second-last item exists.
Our strategy is: run down the list starting with the first item
and ending with the second-last item. If at any time the current
item and the one following it are out of order, swap their elements.
If we made no swaps then the list is sorted, return.
If we made one or more swaps then the list might not be sorted, so
run down the list again.
}
OK, now we can start translating that into code.
void BubbleSort(ListComponent head)
{
// if the list is of zero length then it is already sorted, so return
if (head == null) return;
// if the list is of length one then it is already sorted, so return
if (head.Next == null) return;
// Otherwise, the list is of length two or more. Therefore we know that
// a first item exists and a second-last item exists.
// Our strategy is: run down the list starting with the first item
// and ending with the second-last item.
for (ListComponent current = head;
current.Next != null;
current = current.Next)
{
If at any time the current item and the one following it
are out of order, swap their elements.
}
If we made no swaps then the list is sorted, return.
If we made one or more swaps then the list might not be sorted, so
run down the list again.
}
OK, I've translated some of that English into code. Can you translate the rest?
Another example with a simple class with 2 properties. This is NOT for arrays but for a simple class simulating pointers... Made just for fun !
class MyLinkedList
{
MyLinkedList nextNode;
int data;
public void OrderListBubbleAlgoritm(ref MyLinkedList head)
{
bool needRestart = true;
MyLinkedList actualNode = head; //node Im working with
int temp;
while (needRestart)
{
needRestart = false;
actualNode = head;
while (!needRestart && actualNode.nextNode != null)
{
if (actualNode.nextNode.data >= actualNode.data) //is sorted
{
actualNode = actualNode.nextNode;
}
else
{
//swap the data
temp = actualNode.data;
actualNode.data = actualNode.nextNode.data;
actualNode.nextNode.data = temp;
needRestart = true;
}
}
}
}
}
Remember to use bubble sorting just with small quantity of data.
It's performance is: O(n^2)

How to remove a stack item which is not on the top of the stack in C#

Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between.
Is there a trick to do this?
If you need to remove items that aren't on the top, then you need something other than a stack.
Try making your own implementation of a stack from a List. Then you get to implement your own push and pop functions (add & remove on the list), and your own special PopFromTheMiddle function.
For example
public class ItsAlmostAStack<T>
{
private List<T> items = new List<T>();
public void Push(T item)
{
items.Add(item);
}
public T Pop()
{
if (items.Count > 0)
{
T temp = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return temp;
}
else
return default(T);
}
public void Remove(int itemAtPosition)
{
items.RemoveAt(itemAtPosition);
}
}
Consider using different container. Maybe a LinkedList.
Then you can use
AddFirst
AddLast
RemoveLast
RemoveFirst
just like pop/push from stack and you can use
Remove
to remove any node from the middle of the list
You could use a LinkedList
List based removal will likely be less efficient.
In removal by reference List based stacks will have O(N) search and O(N) resizing. LinkedList search is O(N) and removal is O(1).
For removal by index, LinkedList should have O(N) traversal and O(1) removal, while List will have O(1) traversal (because it is indexing) and O(N) removal due to resizing.
Besides efficiency, a LinkedList implementation will keep you in the standard library, opening your code to more flexibility and have you writing less.
This should be able to handle Pop, Push, and Remove
public class FIFOStack<T> : LinkedList<T>
{
public T Pop()
{
T first = First();
RemoveFirst();
return first;
}
public void Push(T object)
{
AddFirst(object);
}
//Remove(T object) implemented in LinkedList
}
Perhaps an extension method would work, although, I suspect that a different data structure entirely is really needed.
public static T Remove<T>( this Stack<T> stack, T element )
{
T obj = stack.Pop();
if (obj.Equals(element))
{
return obj;
}
else
{
T toReturn = stack.Remove( element );
stack.Push(obj);
return toReturn;
}
}
In a true stack, this can only be done one way -
Pop all of the items until you remove the one you want, then push them back onto the stack in the appropriate order.
This is not very efficient, though.
If you truly want to remove from any location, I'd recommend building a pseudo-stack from a List, LinkedList or some other collection. This would give you the control to do this easily.
Then it is not a stack right? Stack is LAST in FIRST out.
You will have to write a custom one or choose something else.
Stack temp = new Stack();
object x, y;
While ((x = myStack.Pop()) != ObjectImSearchingFor)
temp.Push(x);
object found = x;
While ((y = temp.Pop()) != null)
myStack.Push(y);
A trick I use in hairy situations is adding a 'deprecated' flag to the items in the stack.
When I want to 'remove' an item, I simply raise that flag (and clean up any resources that are taken by the object).
Then when Pop()ing items I simply check if the flag is raised, and pop again in a loop until a non-deprecated item is found.
do
{
obj = mQueue.Pop();
} while (obj.deprecated);
You can manage your own item-count to know how many 'real' items are still in the queue, and obviously locking should be employed if this is required for multi-threaded solution.
I found that for queues that have constant flow through them - items pushed and popped - it's much more efficient to hanle it this way, its the fastest you can get (paying O(1) for removing an item from the middle) and memory wise if the object that is retained is small, it's mostly irrelevant if the items flow in a reasonable pace.
The constructor of a Stack<> takes IEnumerable<> as a parameter. So it would be possible to perform the following:
myStack = new Stack<item>( myStack.Where(i => i != objectToRemove).Reverse() );
This is non performant in a number of ways.
hmmmm...... I agree with the previous two answers but if you are looking to hack your way just pop and save all elements until you get to the one you want, and the re-push them all
Yes is ugly, badly performing, probably weird code that will need a long comment explaining why, but you could do it....
I came across this question. In my code I created my own extension method:
public static class StackExtensions
{
public static void Remove<T>(this Stack<T> myStack, ICollection<T> elementsToRemove)
{
var reversedStack = new Stack<T>();
while(myStack.Count > 0)
{
var topItem = myStack.Pop();
if (!elementsToRemove.Contains(topItem))
{
reversedStack.Push(topItem);
}
}
while(reversedStack.Count > 0)
{
myStack.Push(reversedStack.Pop());
}
}
}
And I call my method like this:
var removedReportNumbers =
selectedReportNumbersInSession.Except(selectedReportNumbersList).ToList();
selectedReportNumbersInSession.Remove(removedReportNumbers);
I used a list and added some extension methods, eg,
public static IThing Pop(this List<IThing> list)
{
if (list == null || list.Count == 0) return default(IThing);
// get last item to return
var thing = list[list.Count - 1];
// remove last item
list.RemoveAt(list.Count-1);
return thing;
}
public static IThing Peek(this List<IThing> list)
{
if (list == null || list.Count == 0) return default(IThing);
// get last item to return
return list[list.Count - 1];
}
public static void Remove(this List<IThing> list, IThing thing)
{
if (list == null || list.Count == 0) return;
if (!list.Contains(thing)) return;
list.Remove(thing); // only removes the first it finds
}
public static void Insert(this List<IThing> list, int index, IThing thing)
{
if (list == null || index > list.Count || index < 0) return;
list.Insert(index, thing);
}
This still processes the whole stack, but it is an alternative to remove an entry. The way this is written though, if the same entry is in the stack multiple times, it will remove them all.
using System.Collections.Generic;
namespace StackTest
{
class Program
{
static void Main(string[] args)
{
Stack<string> stackOne = new Stack<string>();
stackOne.Push("Five");
stackOne.Push("Four");
stackOne.Push("Three");
stackOne.Push("Two");
stackOne.Push("One");
deleteStackEntry(stackOne, #"Three");
deleteStackEntry(stackOne, #"Five");
}
static void deleteStackEntry(Stack<string> st, string EntryToDelete)
{
// If stack is empty
if (st.Count == 0) return;
// Remove current item
string currEntry = st.Pop();
// Remove other items with recursive call
deleteStackEntry(st, EntryToDelete);
// Put all items back except the one we want to delete
if (currEntry != EntryToDelete)
st.Push(currEntry);
}
}
}

Categories

Resources