Singly-linked list/Element definition: Difference between revisions

Content deleted Content added
Rdm (talk | contribs)
J
more examples and explanations
Line 165:
=={{header|J}}==
 
<lang J>list=: ,:_ 0</lang>
list=: 0 2$0
list
</lang>
 
This creates and then displays an empty list, with zero elements. The first number in an item is (supposed to be) the index of the next element inof the list (_ for the final element of the list). The second number in an item is the numeric value ofstored in that list locationitem. The list is named and names are mutable in J which means links are mutable.
 
To create such a list with one element which contains number 42, we can do the following:
 
<lang J>
list=: ,: _ 42
list
_ 42
</lang>
 
Now list contains one item, with index of the next item and value.
 
This solution employs the fact that data types for index and for node content are the same. If we need to store, for example, strings in the nodes, we should do something different, for example:
 
<lang J>
list=: 0 2$a: NB. creates list with 0 items
list
list=: ,: (<_) , <'some text' NB. creates list with 1 item
list
+-+---------+
|_|some text|
+-+---------+
</lang>
 
=={{header|Java}}==