Search code examples
clinked-listediting

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.


Solution

  • Basically your idea is correct except that I wouldn't create a new node. What I would do would be:

    1. Identify if value has increased or decreased (and update node).
    2. Unlink node from the list.
    3. Search forwards or backwards (depending on increase or decrease of grade) for correct location.
    4. 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.