// 反轉鏈表 面試出現率最高 public static LinkList reverseLinkList(LinkList list) { if (list == null || list.head == null || list.head.next == null) { return list; } Node current = list.head;// 舊鏈表的頭結點 Node next;// 用來保存下一下結點 LinkList linkList = new LinkList(); while (current != null) { next = current.next; current.next = linkList.head;// 關鍵代碼 linkList.head = current;// 關鍵代碼 current = next; } return linkList; } // 從尾到頭打印單鏈表:利用棧的特性 public static void printTailLinkList1(LinkList list) { if (list == null || list.head == null) { return; } Stack<Node> stack = new Stack<Node>();// 先進後出 Node current = list.head; while (current != null) { stack.push(current);// push node current = current.next; } while (!stack.isEmpty()) { System.out.print(stack.pop() + "<===");// 彈出pop node } } // 方法:判斷單鏈表是否有環 public static boolean hasCycle(LinkList list) { if (list == null || list.head == null) { return false; } Node frist = list.head; Node second = list.head; while (second != null && frist != null && second.next != null) { frist = frist.next; second = second.next.next; if (frist == second) { return true; } } return false; } // 方法:判斷單鏈表環中結點 public static Node hasCycleNode(LinkList list) { if (list == null || list.head == null) { return null; } Node frist = list.head; Node second = list.head; while (second != null && frist != null && second.next != null) { frist = frist.next; second = second.next.next; if (frist == second) { return frist; } } return null; } // 方法:求單鏈表中環的長度 public static int cycleLength(LinkList list) { Node node = hasCycleNode(list); if (node == null) { return 0; } int count = 1; Node current = node.next; while (current != null && node != current) { count++; current = current.next; } return count; }