Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 957
newbie Avatar asked Jan 21 '23 22:01

newbie


2 Answers

You can accomplish your goal by

  • Removing target node
  • Editing target node data
  • Reinsert the node using your existing logic for inserting nodes.
like image 65
rerun Avatar answered Jan 30 '23 22:01

rerun


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

like image 26
The Archetypal Paul Avatar answered Jan 30 '23 22:01

The Archetypal Paul