Change index in a linked list in c - c

Can anyone help me with finding an algorithm to change a position of a node in a linked list according to the input?
Example:
I have the linked list: 1->2->3->4->END and the user chose the second node and the index 4.
The algorithm will give us the result:
1->3->4->2->END.
Thanks for your help!

It is really easy to move nodes in a linked list because they are done for that...
To change a node's position, just change it's next pointer to the next node address, and the previous node's next pointer to the node you want to move and that's done.

Related

Easiest node to remove from a LinkedList

May I know if there is anything like the easiest node to be removed or deleted from a LinkedList.
I know that deleting a node from in between requires a change of the preceding nodes link, whereas deleting from beginning needs a change of pointer to the new head and deleting from the end needs a change of new end of the list.
But, if asked to delete a node from the LinkedList which is easier which of these should be preferred?
Sounds like you are on the right track with your thoughts on linked lists. Another thing to consider about removing the easiest node from a linked list is the following:
How often will these easiest nodes be removed? If the node is removed from the head of the list the removal will be complete in O(1) time, but if the easiest nodes are at the rear of the list removal will take a full traversal of the list completing in O(n) time.

convert a binary search tree to doubly linklist using recursion

As mentioned in the Title , I have a Binary search tree. I want to convert it to sorted doubly linklist using recursion.
My code
for each node in tree
find max of left sub-tree and assign its right to present node ,present node left to max
find min of right sub-tree and assign its left to present node ,present node right to max
and now recursively do same thing to other nodes in BST .
but this solution is not efficient as it reaches each node more than one time .In my quest of optimized code i got a link from google greatTreeList sollution . I have searched the same in SO both sollutions are same and worked for me. I didnt understand the append function of the sollution as it contains code
join(alast,b)
join(blast,a)
For tree whose nodes are inserted in following order 10,5,9,6,8,7,12,11,13,14
can anyone please explain how
join(alast,b)
join(blast,a)
are linking node in each recursion call.
I think you are over thinking this actually quite easy task - extracting the data from a binary tree in order is as simple as doing a depth first traversal - this is the point of a binary tree that it very efficiently gives you the elements in the sorted order.
So what you need to do is a standard depth first walk of the tree and each time you find a node add it to you linked list.
This in order depth first recursion is fairly straight forward is pseudocode:
Traverse(Node N)
Traverse(N.left);
Add N to the linked list
Traverse(N.right);
I suggest you try this manually on you example so you see how it works.
In order to convert a binary search tree to a sorted doubly linked list, one typically performs an inorder depth-first traversal, building the list along the traversal.
Try to come up with code that performs an inorder depth-first traversal and prints the items of the binary tree in sorted order. From there, it should be easy to complete your task.
Expanding on Elemental's answer
Traverse(Node N)
Traverse(N.left);
Add N to the linked list
Traverse(N.right);
To add N to the linked list,
your linked list class or data structure should have an append() method or similar.
Use your imagination, but something like this:
def append(N):
new_tail = node(val=N, prev=self.tail, next=None)
self.tail.next = new_tail
self.tail = new_tail
of course you also need to add self.head = self.tail the first time you append.

given a singly linked list, how to determine head node from a specified node in C?

given a singly linked list, how to determine head node from a specified node (for e.g say node 4).total # of nodes: 10.Thanks. Logic will do,code is appreciated.
We know given a head node one can perform a forward traverse and determine next node easily.
For this case, use of doubly linked list would be simpler but i was wondering if it is possible to track down head node using singly linked list.Thanks.
Its not possible at all to do that with the kind of singly linked list you've described.
Your question isn't entirely clear. But the only way this is possible is if each of your candidates is the head of a unique list, and one of them is the head that you're after.
For each candidate, traverse the list that starts from it. You will eventually hit the corresponding tail, or you will hit the node in question.
You can also make this work even if your set of candidates are not all heads of unique lists. But you would need logic to detect overlap.
You simply cannot in the singly linked list.
From Wikipedia :
Singly linked lists contain nodes which have a data field as well as a
'next' field, which points to the next node in line of nodes.
You cannot go back to the previous node as you don't have any information about it. If you were given any random node of a singly linked list, the head of your new list will be that node, as you cannot go back any further.

Editing a node in a Linked list

I am creating a student list (linked list) that can add, view and edit student information. I have two fields namely Student Name and Student Grade and I add new students in the list in a way that it is sorted according to the student's grades in descending order.
I have finished doing the add and view portion. The problem is on the edit part because I need to edit the information, then I need to sort it again so that it would be on the proper location of the list.
For example, I have 3 students information arranged according to their grades:
student1 90 -> student2 85 -> student3 80 -> NULL
Then I need to edit student2's grade to 75 so the edited linked list should now be arranged as follows:
student1 90 -> student3 80 -> student2 75 -> NULL
How should I do that? You don't need to give me any code. I just want some advices on how I can implement the edit part of my program. I am thinking of creating a new node (with the edited info), delete the old node and insert the edited node into the list. Is my logic correct? or is there a better way on solving my problem.
You can accomplish your goal by
Removing target node
Editing target node data
Reinsert the node using your existing logic for inserting nodes.
Singly linked list?
Find the node you want to edit, and either keep a pointer to the previous node or write a routine to retrieve the previous node.
Remove your node from the linked list (by setting previous_node->next to thisOne->next)
Make your edits.
Insert the new node in the right place in the list (by traversing the list unti the next node is less than your edited value.
Splice edited into the list ( editedNode->next = nextNode; current->next = editedNode)
With doubly linked lists you can just use the "other"/back/up link to find the previous node
Basically your idea is correct except that I wouldn't create a new node. What I would do would be:
Identify if value has increased or decreased (and update node).
Unlink node from the list.
Search forwards or backwards (depending on increase or decrease of grade) for correct location.
Link node into new location.
Note that indexing the list into an array, etc. may give a quicker search than a linear traversal. If you already have such a mechanism it may be quicker to use that when finding the location to re-insert the node.
You could do a function that edits a specified node. Scan the list until you find that node and then directly edit it. Of course you will use a pointer. For the sorting part, say you have n nodes, compare every node i with the nodes after it and swap them if the one you are comparing with is larger:
for every node n1 in list
for every remaining node n2 in list
if n2->grade > n1->grade
swap 'em
you can swap them copying their memory, so you won't need to change any pointer.

Find the last node of a circular linked list whose size is unknown and the last node points to any other node except first node of the linked list

How can I find last node of a circular linked list whose size I don't know and the last node points to any other node except first node of the linked list?
One algorithm that can be used for this is the Floyd cycle algorithm.
Also, see this question.
By definition, if a node does not point to the first node of a circular linked list,
it is not the last node.
Can you elaborate here?
A strange list... why would you ever need something like this? But anyway...
You can simply iterate over all nodes, and stop as soon as the next node would be one you have already visited. The current node will then be your answer.
You need some way to keep track of which nodes have been visited. Add a boolean flag to each node, or use some kind of set data type with fast insertion and lookup (e.g. a hash set).
Maybe add parameter to nodes of the list which tells you if you at end? I think, it wouldn't be problem.
Otherwise, you can remember nodes you already visted. When the next node is already visited, you are at the end.
The Floyd cycle algorithm won't give the last element of the list. It will only tell if there is a cycle or not.
The definition of the last one would be that, while traversing the list in a sequential scan starting from the first one, all elements before it and the last one aren't seen before (pointer value). The after last one will be the first element that has already been seen in this sequential scan.
An easy solution is to flag visited elements so an element already seen is easily detected. The flag may be intrusive, i.e. by changing a bit in the element, or external by using a hash table to store pointer values.
Since we need to be able to test if an element has already been visited, I don't see another solution.
I can elaborate on how to use Floyd's algorithm to solve this problem but I don't understand the explanation for one step
Have 2 pointers traverse the linked list, pointer 1 going at a rate of 1 node per iteration, the second going at a rate of 2 nodes
When the pointers meet, we are in the cycle and we are some distance before pointer 1 has reached the end of the cycle (we know pointer 1 hasn't reached then end because if cycle is distance d and pointer 2 is going at twice the speed of 1, pointer1 will loop the cycle twice before pointer 1 does it once)
So because they have met before pointer 1 fully traversed the cycle, we know that the meeting point is d nodes from the start and k nodes within the cycle (pos = d + k)
If we set pointer 1 to position 0 and start both points again (but at the same rate rate of 1 node per iteration), they will meet at the start of the cycle.
Since we know the start of the cycle, finding the end is trivial
I don't fully understand why step 4 is true but I had a friend explain the solution to me.

Resources