Reverse local single-chain table (Java version), single-chain java version
Question: There is a linear table (a1, a2, a3 ,..., an), using the single-chain table L storage of the leading node, design an algorithm to reverse the local, linear table into (,... a3, a2, a1 ). The so-called "local" means that the auxiliary storage space is O (1 ).
Solution:
If it is sequential storage, we can easily think of a solution. We can use an auxiliary variable to exchange 1st elements with the nth element, then we use this helper variable to exchange 2nd elements with n-1 elements ,... finally, the auxiliary variable is used to exchange the n/2 elements with the n + 1-n/2 elements.
If "local" is not required, you can create an auxiliary array of n elements, access each element in a single-chain table at a time, and store it in this array, then, access each element in the single-linked list in sequence, and assign values to the elements in the single-linked list from the end of the array until the value of the array's 1st elements is assigned to the last element of the single-linked list.
If a single-chain table is empty or a single-chain table only has a header node, the single-chain table does not need to be reversed. If there is only one element in the single-chain table, its position remains unchanged after the reverse setting, so you can leave it unreversed. When two or more elements exist in a single-chain table, they are disconnected from the first element, leaving its next blank. In turn, 1st elements are accessed to the nth element, when any element is accessed, It is inserted to the header node, that is, it is inserted to the 1st position, in this way, the original 1st elements will be inserted in front of the n-1 elements, the original 2nd elements will be inserted in front of it by the following N-2 elements ,... until the nth element is inserted to the nth position. In this way, the local inversion of the single-chain table of the leading node is realized.
ADT definition:
// The Node class LNode of the single-chain table {// to simplify the access to the single-chain table, the access permission for data items in the node is set to publicpublic int data; public LNode next ;}
Algorithm Implementation:
Public class LinkListUtli {public static void reverse (LNode L) {// The Single-chain table is empty or only has a header node or only one element, if (L = null | L. next = null | L. next. next = null) return; LNode p = L. next. next; // point p to the 2nd elements a2 L in a linear table. next. next = null; // make the next of the first element a1 in the linear table empty while (p! = Null) {LNode q = p. next; // insert p into the header node after p. next = L. next; L. next = p; p = q; // continue to access the next element }}}