I hope I use the correct terminology. I made a list with one chain.
class MyStack { public Node Initial { get; set; } public MyStack() { Initial = null; } public void Push(int data) { var node = new Node { Data = data, Next = Initial }; Initial = node; } public int Pop() { int res = Initial.Data; Initial = Initial.Next; return res; } public int Sum() { int sum = 0; Node currentNode = Initial; while (currentNode != null) { sum += currentNode.Data; currentNode = currentNode.Next; } return sum; } public int Count() { int count = 0; Node currentNode = Initial; while (currentNode != null) { count++; currentNode = currentNode.Next; } return count; } public void PrintAll() { Node currentNode = Initial; while(currentNode != null) { Console.WriteLine("tmp.Data = " + currentNode.Data); currentNode = currentNode.Next; } } } public class Node { public int Data; public Node Next; }
So you can do something like this:
var s = new MyStack(); s.Push(5); s.Push(3); s.Push(7); s.PrintAll(); Console.WriteLine("Sum: " + s.Sum()); Console.WriteLine("Count: " + s.Count());
Now I want to try and do the opposite method. This seems to work:
public void Reverse() { Node predesesor, location; location = Initial; predesesor = null; while(Initial != null) { Initial = Initial.Next; location.Next = predesesor; predesesor = location; location = Initial; } Initial = predesesor; }
I can hardly see how this works, and it will be difficult to maintain. It seems like a hack than anything else.
Can you provide any help?
source share