Linked List reference pointers - linked-list

I am learning linked list operations and have a question related to parameter passing.
Question 1:
I am creating a simple linked list with three values 1->2->3. And am trying to print it.
Below is my code. I am creating a node "first" in my main and am passing it to the method "createlinkedlist". I am using a pointer "head" and updating it within the method. But I see that the values of "head" are retained correctly outside the method "createlinkedlist". I dont understand how this is happening. I was thinking I should use referencial parameter passing like
void createLinkedList(struct node * & head) or void createLinkedList(struct node ** head)
instead of
void createLinkedList(struct node * head)
to get the correct values reflected outside the function. What am I missing here? Why am I able to see the correct values inside the printList method?
struct node
{
int data;
struct node * next;
};
void createLinkedList(struct node * head)
{
struct node * second = (node *)malloc(sizeof(node));
struct node * third = (node *)malloc(sizeof(node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
}
void printList(struct node * first)
{
struct node * current = first;
while(current)
{
printf("%d",current->data);
current = current->next;
}
}
void main()
{
struct node * first = (node *)(malloc(sizeof(node)));
createLinkedList(first);
printList(first);
}
Question 2: I am using the same program as above , but adding a push function
void push(struct node *& first, int data)
{
struct node * newnode = (node*)malloc(sizeof(node));
newnode->data = data;
newnode->next = first;
first = newnode;
}
Now I see that unless I use a "&" for the first parameter in the push(), I am not able to see the updations in the printList method. It makes sense to me because we usually need to use a referncial parameter to make the local function changes seen outside the function. So if the list expects a referencial parameter here, why does it behave differently in the question 1 case.?
Pls. let me know.

Regarding Question 1)
You are not changing the pointer head in your createLinkedList method; you are changing the contents of the node that head points to. So of course you see that change after having called createLinkedList.
Regarding Question 2)
In the second case, you are actually adding a new node and you need to change the head pointer to point to the new head of the linked list, whereas in the first case, you keep the head of the list stable and add new nodes to the tail of the list. So you don't need to get the new address of the head of the list back to the caller, since the address of the head didn't change.
I would also create a node constructor function:
struct node * make_node(int data)
{
struct node * tmp = (node *)malloc(sizeof(node));
if (!tmp) {
/* error handling for malloc failure */
}
tmp->next = NULL;
tmp->data = data;
return tmp;
}
And another point:
If I were you, if I wrote a push function that added nodes to the head of the list, I would return the new head of the list explicitly:
struct node * push(const struct node * head, int data) {
struct node * fresh = make_node(data)
fresh->next = head;
return fresh;
}
Calling this like so:
struct node * head = make_node(1);
head = push(head, 2);
This is easier to understand than figuring out that push(head, 1) changes the head. But it's a question of style.

Change
struct node * first = (node *)(malloc(sizeof(node)));
struct node * second = (node *)(malloc(sizeof(node)));
struct node * third = (node *)(malloc(sizeof(node)));
parts to
struct node * first = (struct node *)(malloc(sizeof(struct node)));
struct node * second = (struct node *)(malloc(sizeof(struct node)));
struct node * third = (struct node *)(malloc(sizeof(struct node)));
. Since you initialized "node" without "typedef", "struct" needs to written before usage of "node" every time.

Since you're talking about references I'll assume you're using C++.
You would want to pass in struct node *& head if you're going to modify the pointer to head, but in your example you want to only modify the head node itself, and not the pointer to it, which is why you simply pass a pointer to it to let you look up the address. When you dereference the pointer via head->... you are looking up the location of head in memory and then moving to its data or next field. Alternatively, you could pass in the head as a reference: struct node & head, and modify things like head.data directly.
Your push needs to have either a reference to the first pointer (struct node *& first), or a pointer to the "first" pointer (struct node **first) so that you can actually modify the pointer itself. This is what's happening on the line:
first = newnode;
Alternatively, if you used struct node **first, you would do:
*first = newnode;
Both cases here for push are modifying a pointer to a struct node, as opposed to modifying a struct node itself.

Related

Can someone explain to me how this code works? Closure in Dart

I can't understand how the closure works in Dart. Why does BMW stay? This explanation causes my neurons to overheat. A lexical closure is a functional object that has access to variables from its lexical domain. Even if it is used outside of its original scope.
`void main() {
var car = makeCar('BMW');
print(makeCar);
print(car);
print(makeCar('Tesla'));
print(car('Audi'));
print(car('Nissan'));
print(car('Toyota'));
}
String Function(String) makeCar(String make) {
var ingane = '4.4';
return (model) => '$model,$ingane,$make';
}`
Console
Closure 'makeCar'
Closure 'makeCar_closure'
Closure 'makeCar_closure'
Audi,4.4,BMW
Nissan,4.4,BMW
Toyota,4.4,BMW
Calling car('Audi') is equal to calling (makeCar('BMW'))('Audi');
A lexical closure is a functional object that has access to variables from its lexical domain. Even if it is used outside of its original scope.
in simple english:
String make will stay valid as long as the returned function is not out of scope because the returned function has reference to String make.
In essence, you "inject" information needed for the newly created function. Your car knows that make is "BMW"
I think I figured it out. Here is an example where I left comments. Maybe it will help someone.
void main() {
var pr = funkOut(10); // assign a reference to an object instance
// of the Function class to the pr variable. pr is a closure because
// it is assigned a reference to an instance that contains a lexical
// environment (int a) and an anonymous function from this environment.
// 10 transfer to a
print(pr(5)); // 5 transfer to b //15
print(pr(10)); // 10 transfer to b //20
pr = funkOut(20);// 20 transfer to a
print(pr(5)); // 5 transfer to b //25
print(pr); // Closure: (int) => int
}
Function funkOut(int a) {
return (int b) => a + b;
}

How to modify a functions internal variables at runtime and pass it to another function?

Functions in Dart are first-class objects, allowing you to pass them to other objects or functions.
void main() {
var shout = (msg) => ' ${msg.toUpperCase()} ';
print(shout("yo"));
}
This made me wonder if there was a way to modify a function a run time, just like an object, prior to passing it to something else. For example:
Function add(int input) {
return add + 2;
}
If I wanted to make the function a generic addition function, then I would do:
Function add(int input, int increment) {
return add + increment;
}
But then the problem would be that the object I am passing the function to would need to specify the increment. I would like to pass the add function to another object, with the increment specified at run time, and declared within the function body so that the increment cannot be changed by the recipient of the function object.
The answer seems to be to use a lexical closure.
From here: https://dart.dev/guides/language/language-tour#built-in-types
A closure is a function object that has access to variables in its
lexical scope, even when the function is used outside of its original
scope.
Functions can close over variables defined in surrounding scopes. In
the following example, makeAdder() captures the variable addBy.
Wherever the returned function goes, it remembers addBy.
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
void main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
In the above cases, we pass 2 or 4 into the makeAdder function. The makeAdder function uses the parameter to create and return a function object that can be passed to other objects.
You most likely don't need to modify a closure, just the ability to create customized closures.
The latter is simple:
int Function(int) makeAdder(int increment) => (int value) => value + increment;
...
foo(makeAdder(1)); // Adds 1.
foo(makeAdder(4)); // Adds 2.
You can't change which variables a closure is referencing, but you can change their values ... if you an access the variable. For local variables, that's actually hard.
Mutating state which makes an existing closure change behavior can sometimes be appropriate, but those functions should be very precise about how they change and where they are being used. For a function like add which is used for its behavior, changing the behavior is rarely a good idea. It's better to replace the closure in the specific places that need to change behavior, and not risk changing the behavior in other places which happen to depend on the same closure. Otherwise it becomes very important to control where the closure actually flows.
If you still want to change the behavior of an existing global, you need to change a variable that it depends on.
Globals are easy:
int increment = 1;
int globalAdder(int value) => value + increment;
...
foo(globalAdd); // Adds 1.
increment = 2;
foo(globalAdd); // Adds 2.
I really can't recommend mutating global variables. It scales rather badly. You have no control over anything.
Another option is to use an instance variable to hold the modifiable value.
class MakeAdder {
int increment = 1;
int instanceAdd(int value) => value + increment;
}
...
var makeAdder = MakeAdder();
var adder = makeAdder.instanceAdd;
...
foo(adder); // Adds 1.
makeAdder.increment = 2;
foo(adder); // Adds 2.
That gives you much more control over who can access the increment variable. You can create multiple independent mutaable adders without them stepping on each other's toes.
To modify a local variable, you need someone to give you access to it, from inside the function where the variable is visible.
int Function(int) makeAdder(void Function(void Function(int)) setIncrementCallback) {
var increment = 1;
setIncrementCallback((v) {
increment = v;
});
return (value) => value + increment;
}
...
void Function(int) setIncrement;
int Function(int) localAdd = makeAdder((inc) { setIncrement = inc; });
...
foo(localAdd); // Adds 1.
setIncrement(2);
foo(localAdd); // Adds 2.
This is one way of passing back a way to modify the local increment variable.
It's almost always far too complicated an approach for what it gives you, I'd go with the instance variable instead.
Often, the instance variable will actually represent something in your model, some state which can meaningfully change, and then it becomes predictable and understandable when and how the state of the entire model changes, including the functions referring to that model.
Using partial function application
You can use a partial function application to bind arguments to functions.
If you have something like:
int add(int input, int increment) => input + increment;
and want to pass it to another function that expects to supply fewer arguments:
int foo(int Function(int input) applyIncrement) => applyIncrement(10);
then you could do:
foo((input) => add(input, 2); // `increment` is fixed to 2
foo((input) => add(input, 4); // `increment` is fixed to 4
Using callable objects
Another approach would be to make a callable object:
class Adder {
int increment = 0;
int call(int input) => input + increment;
}
which could be used with the same foo function above:
var adder = Adder()..increment = 2;
print(foo(adder)); // Prints: 12
adder.increment = 4;
print(foo(adder)); // Prints: 14

Coding a type of random walk in Neo4j using the Traversal Framework

I'm currently working on a graph where nodes are connected via probabilistic edges. The weight on each edge defines the probability of existence of the edge.
Here is an example graph to get you started
(A)-[0.5]->(B)
(A)-[0.5]->(C)
(B)-[0.5]->(C)
(B)-[0.3]->(D)
(C)-[1.0]->(E)
(C)-[0.3]->(D)
(E)-[0.3]->(D)
I would like to use the Neo4j Traversal Framework to traverse this graph starting from (A) and return the number of nodes that have been reached based on the probability of the edges found along the way.
Important:
Each node that is reached can only be counted once. -> If (A) reaches (B) and (C), then (C) need not reach (B). On the other hand if (A) fails to reach (B) but reaches (C) then (C) will attempt to reach (B).
The same goes if (B) reaches (C), (C) will not try and reach (B) again.
This is a discrete time step function, a node will only attempt to reach a neighboring node once.
To test the existence of an edge (whether we traverse it) we can generate a random number and verify if it's smaller than the edge weight.
I have already coded part of the traversal description as follows. (Here it is possible to start from multiple nodes but that is not necessary to solve the problem.)
TraversalDescription traversal = db.traversalDescription()
.breadthFirst()
.relationships( Rels.INFLUENCES, Direction.OUTGOING )
.uniqueness( Uniqueness.NODE_PATH )
.uniqueness( Uniqueness.RELATIONSHIP_GLOBAL )
.evaluator(new Evaluator() {
#Override
public Evaluation evaluate(Path path) {
// Get current
Node curNode = path.endNode();
// If current node is the start node, it doesn't have previous relationship,
// Just add it to result and keep traversing
if (startNodes.contains(curNode)) {
return Evaluation.INCLUDE_AND_CONTINUE;
}
// Otherwise...
else {
// Get current relationhsip
Relationship curRel = path.lastRelationship();
// Instantiate random number generator
Random rnd = new Random();
// Get a random number (between 0 and 1)
double rndNum = rnd.nextDouble();
// relationship wc is greater than the random number
if (rndNum < (double)curRel.getProperty("wc")) {
String info = "";
if (curRel != null) {
Node prevNode = curRel.getOtherNode(curNode);
info += "(" + prevNode.getProperty("name") + ")-[" + curRel.getProperty("wc") + "]->";
}
info += "(" + curNode.getProperty("name") + ")";
info += " :" + rndNum;
System.out.println(info);
// Keep node and keep traversing
return Evaluation.INCLUDE_AND_CONTINUE;
} else {
// Don't save node in result and stop traversing
return Evaluation.EXCLUDE_AND_PRUNE;
}
}
}
});
I keep track of the number of nodes reached like so:
long score = 0;
for (Node currentNode : traversal.traverse( nodeList ).nodes())
{
System.out.print(" <" + currentNode.getProperty("name") + "> ");
score += 1;
}
The problem with this code is that although NODE_PATH is defined there may be cycles which I don't want.
Therefore, I would like to know:
Is there is a solution to avoid cycles and count exactly the number of nodes reached?
And ideally, is it possible (or better) to do the same thing using PathExpander, and if yes how can I go about coding that?
Thanks
This certainly isn't the best answer.
Instead of iterating on nodes() I iterate on the paths, and add the endNode() to a set and then simply get the size of the set as the number of unique nodes.
HashSet<String> nodes = new HashSet<>();
for (Path path : traversal.traverse(nodeList))
{
Node currNode = path.endNode();
String val = String.valueOf(currNode.getProperty("name"));
nodes.add(val);
System.out.println(path);
System.out.println("");
}
score = nodes.size();
Hopefully someone can suggest a more optimal solution.
I'm still surprised though that NODE_PATH didn't not prevent cycles from forming.

Deleting a node from the middle of a link list, function prototype is: int particle_remove(struct particle* p);

I have been working on this for like 10 hours.
int particle_remove(struct particle* p);
How do I find the head when I'm passing the location of the "node-to-be-deleted" to the function?
I know that:
prev->next = curr->next;
free(curr);
how do I find the location of the head to traverse down to (curr -1)?
This is what I have so far:
int particle_remove(struct particle *p){
struct particle *curr = p;
struct particle *prev = *head; /* should point to the head */
if (p != NULL){
while (prev != curr){
prev=curr->next;
}
prev->next = curr->next;
free(curr);
}
return 0;
}
I have been over this a million times and I can't think of how to get to the head node, without passing a parameter of the location of the head node into the function. Is it possible to do this with the current function "signature" or do I have to add a reference to the head?
OK I have figured it out by creating a new function that takes both the current node to be destroyed and a pointer to the head, as I don't believe that just using a function to the node to be deleted will work as there is no reference to the head. (Unless someone can prove me wrong, please do!)
I ended up with a prototype that looks like this: (for those that are looking for a hint)
int particle_remove(struct particle *p, struct particle **head);
The problem is: you have to change the head pointer if the pointer to be deleted (p) happens to be first in the list. Using a pointer-to-pointer (a pointer to the head pointer) is the easiest way:
int particle_remove(struct particle *p){
struct particle **pp; /* should point to the head */
for(pp = &head; *pp; pp = &(*pp)->next){
if (*pp != p) continue;
*pp = p->next;
free(p);
break;
}
return 0;
}
If head is not a gobal pointer, you indeed end up with a function where the pointer to head is passed as an argument:
int particle_remove(struct particle **pphead, struct particle *p){
for( ; *pphead; pphead = &(*pphead)->next){
if (*pphead != p) continue;
*pphead = p->next;
free(p);
break;
}
return 0;
}
BTW: the return value is nonsense. If there is no useful return for the function, it could just as well return void.
OK, so the way to solve this using the original function prototype is if you use:
if(p->next != NULL){
/* do something */
}
You are checking to see if the next node is to be deleted. This gives you access to the previous node and the next node (to be deleted).

Get to know the layer order in the flash timeline via as3 code

Is there any method with which I can get to know which of the two movieclips I'm using is lying above or below in the timeline 'layer' arrangement in flash.
what I'm asking is if have two movieclips 'a' and 'b'. One in layer 10 of timeline of flash professional and 'b' on layer 1. Will be able to change the index order using pure as3 code to visually keep the movieclip on the 10th layer on top of the movieclip on 1st layer??
Thank you.
Vishnu
[[Edit]]
The attached method will not work if both target objects are leaf nodes in a shared parent.
The timeline children are always under whatever actionscript generated children are associated to the timeline class.
e.g.
If you have timeline X, which extends ClassA, and in Class A, you add children E, F, G, but timeline X contains layers B, C, D, each with a single symbol in each layer, with layer B at the bottom of the timeline, the following would be observed:
child 5: G
child 4: F
child 3: E
child 2: D
child 1: C
child 0: B
To expand on a felipemaia's answer, I've devised the following method to determine which movie clip lies absolutely above the other. This has not been thoroughly tested, but should operate as a baseline for your development.
function selectAbove(obj1:DisplayObject, obj2:DisplayObject):DisplayObject
{
var obj1_parentCount:int = parentCount(obj1);
var obj2_parentCount:int = parentCount(obj2);
var target:DisplayObject;
var other:DisplayObject;
if (obj1_parentCount > obj2_parentCount)
{
target = obj1;
other = obj2;
}
else
{
target = obj2;
other = obj1;
}
var container:DisplayObjectContainer =
(target is DisplayObjectContainer) ? target as DisplayObjectContainer : target.parent ;
var container_last:DisplayObjectContainer;
var sharedParent:DisplayObjectContainer;
while(container)
{
if(container.contains(other))
{
sharedParent = container;
break;
}
container_last = container;
container = container.parent;
}
if(!sharedParent)
{
throw new Error("An object does not maintain its parent in the display heirarchy!");
}
var ret:DisplayObject;
if(container == other)
{
ret = target;
}
return container != other ?
container.getChildIndex(container_last) < container.getChildIndex(other) ?
other :
target
:
target
;
}
function parentCount(obj:DisplayObject):int
{
var ret:int = 0;
while(obj)
{
ret++;
obj = obj.parent;
}
return ret;
}
This method will work for nested display hierarchies. I have not tested this 100%, but initial cases completed as expected.
Best of luck!
To verify which DisplayObject is on top, you're gonna have to compare their indexes with the getChildIndex() method:
var mc1 : MovieClip;
var mc2 : MovieClip;
// THIS CODE ASSUMES THAT mc1 and mc2 HAVE THE SAME PARENT
var parentMC : MovieClip = MovieClip(mc1.parent);
var topmost : MovieClip = parentMC.getChildIndex(mc1) < parentMC.getChildIndex(mc2) ? mc1 : mc2;
The one who has the lowest index is the topmost one.
EDIT:
As long as the MovieClips have the same parent, you can manipulate the index of the objects with swapChildren(), swapChildrenAt(), and setChildIndex(). So to bring a MovieClip to the topmost front, you would do MovieClip(parent).setChildIndex(this, 0);
I don't think there are layers in the context of ActionScript, but you can determine which instances of DisplayObject are further up using:
DisplayObjectContainer . getChildIndex()

Resources