A series of questions about linked lists are described earlier, and here we introduce a more representative algorithm for the reversal of unidirectional lists. In the reversal of the time must remember the multi-drawing, more to understand when the list is reversed when it changes the address, this and the array of data is very inconsistent.
Publicnode reverselist (node head) {//determine if a linked list is empty or if there is only one node if(Head = =NULL|| Head.next = =NULL){ returnHead; } //Prepare three nodesNode next =NULL;//Save the next node of the current nodeNode reverse =NULL;//reverses the head node of the linked list laterNode current = head;//the node that is currently being reversed while(Current! =NULL){ //Save the next node of the current nodeNext =Current.next; //converts a head node to the next node of the current nodeCurrent.next =reverse; //assign a value to the head node.Reverse =Current ; //moves the current node backCurrent =Next; } returnreverse;}
The important thing to say three times, address conversion is very important! Address Translation is important! Address Translation is important!
About the deletion of one-way linked list Why am I here alone to say that this is the basic operation of a one-way list, but can we think of a problem. In the front we said the address translation of this thing, if we are in the deletion, the node will be deleted the next node to assign value to the deleted node, and then the next node becomes empty, then we do not implement the delete operation. The code is as follows:
Public Booleandeletenode (Node delete) {//determine if the linked list is empty if(Head = =NULL){ return false; } //determine if the node is a tail node if(Delete.next = =NULL) {Delete=NULL; return true; } //find the next node that needs to delete the nodeNode next =Delete.next//assigns the value of the next node to the delete node and empties the Delete node informationDelete =Next; Next=NULL; return true; }
The deleted code just provides the idea that the code needs to be rewritten on its own. The benefits of this writing are obvious, and we can only spend O (1) at the time of deletion, if we go to get the previous node of the delete node, we can take much more time than that. Of course this is built in the list must have this node premise, if the list node exists need we ourselves to judge that nature is unable to complete, because so convenient a list of time is O (N).
Data structure and algorithm one-way link List VI: The reversal of the list and the deletion of the linked list node