Editing a node in a linked list

I create a student list (linked list) that can add, view and edit student information. I have two fields, namely: the name of the student and the class of students, and I add new students to the list so that they are sorted according to the degrees of students in descending order.

I finished doing the add and browse. The problem is in the editing part, because I need to edit this information, then I need to sort it again so that it is in the correct location of the list.

For example, I have information about three students according to my grades:

student1 90 -> student2 85 -> student3 80 -> NULL 

Then I need to edit class student2 to 75 so that the edited linked list is now ordered as follows:

 student1 90 -> student3 80 -> student2 75 -> NULL 

How can I do it? You do not need to give me the code. I just need some tips on how I can implement the editing part of my program. I am going to create a new node (with edited information), delete the old node and insert the edited node into the list. Is my logic correct? or is there a better way to solve my problem.

+4
source share
4 answers

Basically, your idea is correct, except that I would not create a new node. I would do this:

  • Determine if the value has increased or decreased (and the node has been updated).
  • Disable node from the list.
  • Search in the opposite direction or in the opposite direction (depending on the increase or decrease in level) for the correct location.
  • Link node to a new location.

Note that indexing a list into an array, etc. may give a faster search than a linear crawl. If you already have such a mechanism, it might be faster to use when searching for a place to reinstall node.

+2
source

You can complete your task

  • Delete target node
  • Editing target node data
  • Insert node using existing logic to insert nodes.
+3
source

Single list?

Find the node you want to edit and save the pointer to the previous node or write a procedure to get the previous node.

Extract node from linked list (by setting previous_node-> next to thisOne-> next)

Make your changes.

Paste the new node at the desired location in the list (by going through the list until the next node is smaller than your edited value.

A splice edited in the list (editedNode-> next = nextNode; current-> next = editNode)

With doubly linked lists, you can simply use the β€œother” / back / up link to find the previous node

+3
source

You can execute a function that edits the 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, let's say you have n nodes, compare each node I with the nodes after it and replace 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 their copies of your memory, so you won’t need to change any pointer.

+1
source

All Articles