Ideas for realization:
1. First create a temporary single-linked list single2.
2. Remove the elements of the original list single one by one, which is equivalent to deleting in the process of extracting.
(1) When it is taken out, it is necessary to point single's head pointer to its next headNode.next = headNode.next.next;
2) When removing res = headNode.next, delete res.next = null
3. Place each extracted element in single2, but insert the following figure from scratch.
4. Print the headNode.next = single2.getHead().next of a single, which is a single chain table after inversion or reverse order.
The code is as follows:
Person:
public class Person { public int id; public String name; public Person next; public Person(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
SingleLinkedList:
public class SingleLinkedList { private Person head = new Person(0,""); // Add to public void add(Person person){ Person temp = head; // Find the last one and add it again while(true){ if (temp.next == null){ // It's already in the last place. temp.next = person; break; } temp = temp.next; } } // count public int getCount(Person headNode){ Person temp = headNode; int count= 0; while(true){ if(temp.next == null){ break; } count++; temp = temp.next; } return count; } // Getting Header Node public Person getHead(){ return head; } // Remove the nth node public Person getNode(Person headNode){ Person temp = headNode; if(headNode.next == null){ throw new RuntimeException("The list is empty..."); } Person res = temp.next; temp.next = temp.next.next; res.next = null; return res; } // Put the node in the first place public void addNodeAtFirst(Person headNode,Person node){ Person temp = headNode; if (temp.next == null){ temp.next = node; return; } node.next = headNode.next; headNode.next = node; } // Display all nodes public void show(Person headNode){ if(headNode.next == null){ throw new RuntimeException("The list is empty..."); } Person temp = headNode.next; while(true){ if(temp == null) { break; } System.out.println(temp); temp = temp.next; } } }
Test class:
public class LinkedListCount { public static void main(String[] args) { Person person1 = new Person(1,"zs"); Person person2 = new Person(2,"ls"); Person person3 = new Person(3,"ww"); SingleLinkedList single = new SingleLinkedList(); single.add(person1); single.add(person2); single.add(person3); // Get the Head Node single.show(single.getHead()); // Reversal int count = single.getCount(single.getHead()); SingleLinkedList single2 = new SingleLinkedList(); for (int i = 0; i < count ; i++) { Person node = single.getNode(single.getHead()); single2.addNodeAtFirst(single2.getHead(),node); } single.getHead().next = single2.getHead().next; single.show(single.getHead()); } }