Mainly in the interview may often encounter the similar operation, especially slightly larger company, the interviewer may not care whether you can solve the problem, but this type of topic is the most can reflect the programmer's state of mind---a confused programmer how can aspire to change the world
/** * @author Luochengcheng * Define a single linked list */class node {//variable private int record;//point to Next object private node Nextnode;public node (int Record) {super (); this.record = record;} public int Getrecord () {return record;} public void Setrecord (int record) {This.record = record;} Public Node Getnextnode () {return nextnode;} public void Setnextnode (Node nextnode) {this.nextnode = NextNode;}} /** * @author Luochengcheng * Two ways to achieve single-linked list reversal (recursive, normal) * Novice highly recommended to take the paper and pen next to the code drawing (easy to understand) */public class Reversesinglelist {/** * recursion, in the anti- Reverses the next node before going to the current node */public static node reverse (node head) {if (null = = Head | | null = = Head.getnextnode ()) {return head;} Node reversedhead = reverse (Head.getnextnode ()); Head.getnextnode (). Setnextnode (head); Head.setnextnode (null); return reversedhead;} /** * Traversal, the next node of the current node is cached after the current node pointer is changed * */public static nodes Reverse2 (node head) {if (null = = head) {return head;} Node pre = head; Node cur = head.getnextnode (); Node next;while (null! = cur) {next = Cur.getnextnode (); Cur.setnextnode (pre);p re = cur;cur = Next;} The original chainThe next node of the table's head node is set to null, and the inverted head node is assigned to head head.setnextnode (null); head = Pre;return head;} public static void Main (string[] args) {node head = new Node (0); Node tmp = NULL; Node cur = null;//Constructs a linked list of length 10, which holds the head node object head for (int i = 1; i <; i++) {tmp = new Node (i); if (1 = = i) {Head.setnext Node (TMP);} else {cur.setnextnode (TMP);} cur = tmp;} Print the linked list before inversion node h = head;while (null! = h) {System.out.print (H.getrecord () + ""); h = H.getnextnode ();} Call reversal Method head = Reverse2 (head); System.out.println ("\n**************************");//print reversed result while (null! = Head) {System.out.print (Head.getrecord () + ""); head = Head.getnextnode ();}}}
Java inverted single-linked list (code)