// 反转链表 面试出现率最高
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;
}
转载于:https://my.oschina.net/u/2477353/blog/651575