Reputation: 3
I've read a code of Stack implementation in C#.
The code is working but I don't understand whether it is illegal (I am sure it is legal as I can compile it) to have a object of a class inside the same class. The code is as follows.
public class Stack{
Entry top;
public void Push(object data){
top = new Entry(top, data);
}
public object Pop(){
if(top==null) throw new InvalidOperationException();
object result = top.data;
top = top.next;
return result;
}
class Entry{
public Entry next;//?
public object data;
public Entry(Entry next, object data){
this.next = next;
this.data = data;
}
}
}
The code is compiled and running ok.
I am confused that inside of the Entry class, it has a field next
of Entry class.
Furthermore, when Stack is calling Push method, it calls the Entry constructor, which set this.next
to next
, but I don't understand how this works, this.next
will point to object next
, but where and how the object "next" being created.
I am very appreciated if someone could help me to understand the above code.
Upvotes: 0
Views: 65
Reputation: 2417
Work flow like that
Push() , top = new Entry(top, data);
(A) , top.next
<--- null
Push() , top = new Entry(top, data);
(B) , top.next
<--- (A)
Push() , top = new Entry(top, data);
(C), top.next
<--- (B)
Pop() , return (C) , top = (B);
Pop() , return (B) , top = (A);
Pop() , return (A) , top = null ;
Pop() , throw InvalidOperationException
because top == null
now.
And your first question (where and how the object "next" being created)
First push is SPECIALY, it's next is null , But it's ok , because when pop() , It have null check.
Upvotes: 0
Reputation: 271990
The field next
stores a reference to another object of Entry
, or a null reference. Note that next
could be null!
Your confusion probably comes from the misconception that to create an Entry
, you must need an instance of Entry
first, which seems quite circular on first sight. However, note that you could pass null
as the first parameter:
Entry entry1 = new Entry(null, someObject);
Essentially, Entry
represents a node in a linked list, which in turn is used to implement the stack:
A ---> B ---> C
The next
of A
is B
. next
of B
is C
. What's the next
of C
? It's null
!
Upvotes: 3