注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
1,单/双链表的逆序
package sword_to_offer_linkedlist;
public class ReverseList {
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next; // 把下一个节点存储起来
head.next = pre; // 把当前节点的指针指向前一个节点
pre = head; // 把当前节点作为下一个节点的前一个节点
head = next; // 把刚刚存储好的下一个节点作为当前节点
}
return pre;
}
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next; // 把下一个节点存储起来
head.next = pre; // 把当前节点的next指针指向前一个节点
head.last = next; // 把当前节点的last指针指向下一个节点
pre = head; // 把当前节点作为下一个节点的前一个节点
head = next; // 把刚刚存储好的下一个节点作为当前节点
}
return pre;
}
public static void printLinkedList(Node head) {
System.out.print("Linked List: ");
while (head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
public static void printDoubleLinkedList(DoubleNode head) {
System.out.print("Double Linked List: ");
DoubleNode end = null;
System.out.print("head to end: ");
while (head != null) {
System.out.print(head.value + " ");
end = head;
head = head.next;
}
System.out.print(" | ");
System.out.print("end to head: ");
while (end != null) {
System.out.print(end.value + " ");
end = end.last;
}
System.out.println();
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
System.out.println("Before reverse: ");
printLinkedList(head1);
System.out.println("After reverse: ");
printLinkedList(reverseList(head1));
System.out.println("========================================");
DoubleNode head2 = new DoubleNode(1);
head2.next = new DoubleNode(2);
head2.next.last = head2;
head2.next.next = new DoubleNode(3);
head2.next.next.last = head2.next;
head2.next.next.next = new DoubleNode(4);
head2.next.next.next.last = head2.next.next;
System.out.println("Before reverse: ");
printDoubleLinkedList(head2);
System.out.println("After reverse: ");
printDoubleLinkedList(reverseList(head2));
}
}
2、打印两个有序链表的公共部分
package sword_to_offer_linkedlist;
public class PrintCommonPartBetweenTwoSortedLinkedList {
// 打印两个有序链表的公共部分
// 思路:外排
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static void printCommonPartBetweenTwoSortedLinkedList(Node head1, Node head2) {
System.out.print("Common Part: ");
// 谁小跳过谁
while (head1 != null && head2 != null) {
if (head1.value < head2.value) {
head1 = head1.next;
} else if (head1.value > head2.value) {
head2 = head2.next;
} else { // head1.value == head2.value
System.out.print(head1.value + " ");
head1 = head1.next;
head2 = head2.next;
}
}
System.out.println();
}
public static void printLinkedList(Node head) {
if (head == null) return;
System.out.print("Linked List: ");
while (head.next != null) {
System.out.print(head.value + " -> ");
head = head.next;
}
System.out.println(head.value);
}
public static void main(String[] args) {
Node head1 = new Node(2);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(6);
Node head2 = new Node(1);
head2.next = new Node(2);
head2.next.next = new Node(5);
head2.next.next.next = new Node(7);
head2.next.next.next.next = new Node(8);
printLinkedList(head1);
printLinkedList(head2);
printCommonPartBetweenTwoSortedLinkedList(head1, head2);
}
}
3、O(1)时间删除链表中的指定节点
package sword_to_offer_linkedlist;
public class DeleteOneNodeInLinkedList {
public static class Node {
int value;
Node next = null;
Node(int value) {
this.value = value;
}
}
public static Node deleteOneNode(Node head, Node toBeDeleted) {
// 如果head或者toBeDeleted为null,返回head
if (head == null | toBeDeleted == null) return head;
// 如果即将删除的节点是最后一个节点
if (toBeDeleted.next == null) {
// 如果即将删除的节点既是最后一个节点也是第一个节点,即只有一个节点时
if (head == toBeDeleted) {
head = null; // head被覆盖了,指向null
return head;
} else { // 如果只是最后一个节点而不是第一个节点,即链表至少有两个节点,toBeDeleted有前一个节点,使用遍历将前一个节点的next指针指向null
Node cur = head;
while (cur.next != toBeDeleted) {
cur = cur.next;
}
cur.next = null;
return head;
}
}
toBeDeleted.value = toBeDeleted.next.value;
toBeDeleted.next = toBeDeleted.next.next;
return head;
}
public static void printLinkedList(Node head) {
if (head == null) return;
Node pNode = head;
while (pNode.next != null) {
System.out.print(pNode.value + "->");
pNode = pNode.next;
}
System.out.println(pNode.value);
}
public static void main(String[] args) {
Node head = new Node(1);
/*Node node1 = new Node(2);
Node node2 = new Node(3);
head.next = node1;
node1.next = node2;*/
System.out.println("删除节点之前:");
printLinkedList(head);
deleteOneNode(head, head);
System.out.println("删除节点之后:");
printLinkedList(head);
System.out.println("============================");
Node head1 = new Node(1);
/* Node node11 = new Node(2);
Node node12 = new Node(3);
head1.next = node11;
node11.next = node12;*/
System.out.println("删除节点之前:");
printLinkedList(head1);
System.out.println("带返回值删除节点之后:");
printLinkedList(deleteOneNode(head1, head1));
}
}
4、将有序链表中多个重复节点变成一个
package sword_to_offer_linkedlist;
public class ChangeDuplicateNodeToOnce {
public static class Node {
int value;
Node next = null;
Node(int value) {
this.value = value;
}
}
public static Node changeDuplicateNodeToOnce(Node head) {
if (head == null) return null;
Node cur = head.next; // 当前节点
Node preNode = head; // 当前节点的前一个节点
while (cur != null) {
// 比较我和我的前一个数是否相等
if (cur.value == preNode.value) {
// 如果相等,删除前一个节点(把要删除的节点的下一个节点的值赋给这个要删除的节点的位置,再让当前节点指向.next.next)
preNode.value = preNode.next.value;
preNode.next = preNode.next.next;
cur = cur.next;
continue;
}
preNode = cur; // 当前节点作为下一轮的前一个节点
cur = cur.next; // 当前节点的下一个节点作为下一轮的当前节点
}
return head;
}
public static void printLinkedList(Node head) {
if (head == null) return;
//System.out.print("Linked List: ");
while (head.next != null) {
System.out.print(head.value + " -> ");
head = head.next;
}
System.out.println(head.value);
}
public static void main(String[] args) {
Node head = new Node(1);
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(3);
Node node4 = new Node(3);
Node node5 = new Node(4);
Node node6 = new Node(4);
head.next = node1;
head.next.next = node2;
head.next.next.next = node3;
head.next.next.next.next = node4;
head.next.next.next.next.next = node5;
head.next.next.next.next.next.next = node6;
System.out.println("删除重复节点前:");
printLinkedList(head);
System.out.println("删除重复节点后:");
printLinkedList(changeDuplicateNodeToOnce(head));
}
}
5、删除链表中所有重复节点
在4的基础上修改需求为:只要重复的话,一个都不剩
package sword_to_offer_linkedlist;
public class DeleteDuplicateNodeInSortedLinkedList {
public static class Node {
int value;
Node next = null;
Node(int value) {
this.value = value;
}
}
public static Node deleteDuplicateNode(Node head) {
if (head == null) return null;
Node pre = null; // 当前节点的前一个节点
Node cur = head; // 当前节点
while (cur != null) {
Node pos = cur.next;
boolean needDelete = false;
// 如果我和后一个节点的值相等,则将我标志为需要删除
if (pos != null && cur.value == pos.value) {
needDelete = true;
}
if (!needDelete) { // 如果不需要删除我
pre = cur;
cur = cur.next;
} else { // 如果需要删除我,则找到所有相等的值都删除,将pre指向第一个不重复的值pos
int dupValue = cur.value;
while (cur != null && cur.value == dupValue) {
cur = cur.next;
pos = cur;
} // 跳出循环的条件是找到了第一个cur后面不重复的值pos,或者直到找到最后一个值都没找到不重复的值
if (pre == null) { // 如果删除的节点是头结点
head = pos; // 则把pos作为头结点
} else {
pre.next = pos; // 否则将pos接上pre
}
cur = pos; // pos作为下一个cur
}
}
return head;
}
public static void printLinkedList(Node head) {
if (head == null) return;
//System.out.print("Linked List: ");
while (head.next != null) {
System.out.print(head.value + " -> ");
head = head.next;
}
System.out.println(head.value);
}
public static void main(String[] args) {
Node head = new Node(3);
Node node1 = new Node(3);
Node node2 = new Node(3);
Node node3 = new Node(3);
Node node4 = new Node(3);
Node node5 = new Node(3);
Node node6 = new Node(3);
//Node node7 = new Node(4);
head.next = node1;
head.next.next = node2;
head.next.next.next = node3;
head.next.next.next.next = node4;
head.next.next.next.next.next = node5;
head.next.next.next.next.next.next = node6;
//head.next.next.next.next.next.next.next = node7;
System.out.println("删除重复节点前:");
printLinkedList(head);
System.out.println("删除重复节点后:");
printLinkedList(deleteDuplicateNode(head));
}
}
6、判断链表是否为回文结构
package sword_to_offer_linkedlist;
import java.util.Stack;
public class IsPalindromeLinkedList {
// 判断一个链表是否为回文结构
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
// 方法1:用一个辅助栈,将链表中的元素和栈中逆序的元素一一比较,每一个值都相等则为回文结构,空间复杂度O(n)
public static boolean isPalindrome1(Node head) {
if (head == null || head.next == null) {
return true;
}
Stack<Node> stack = new Stack<>();
Node cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while (head != null) {
if (head.value != stack.pop().value) {
return false;
}
head = head.next;
}
return true;
}
// 方法2:快指针一次走两步,慢指针一次走一步,快指针走完慢指针来到几乎中点的位置
// 慢指针之后走的压入栈中,实际上是把后半段逆序和前半段比较,空间复杂度O(n/2)
public static boolean isPalindrome2(Node head) {
Stack<Node> stack = new Stack<>();
if (head == null || head.next == null) {
return true;
}
Node slow = head.next; // 考虑到奇偶数,应该把slow往后一步
Node fast = head;
// 奇数时慢指针来到中点的后一个位置,偶数时慢指针来到两个中点的后一个位置
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
while (slow != null) {
stack.push(slow);
slow = slow.next;
}
while (!stack.isEmpty()) {
if (head.value != stack.pop().value) {
return false;
}
head = head.next;
}
return true;
}
// 方法3:完全不用辅助空间,空间复杂度O(1)
// 快指针一次走两步,慢指针一次走一步,快指针走完慢指针来到几乎中点的位置
// 把慢指针后面的后半部分逆序,再一个从尾部开始走,一个从头部开始走,遇到空的还没发现不同则是回文链表
// 由于要保证原来的结构,故把后半部分逆序的再调整回去
public static boolean isPalindrome3(Node head) {
if (head == null || head.next == null) {
return true;
}
Node slow = head;
Node fast = head;
// 奇数时慢指针来到中点位置,偶数时慢指针来到两个中点的前一个位置
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 记录中点的位置
Node mid = slow;
Node pre = null;
Node cur = slow;
// 把慢指针后面的后半部分逆序
while (cur != null) {
Node pos = cur.next; // 把当前节点的下一个节点记录下来
cur.next = pre; // 把cur的next指向前一个节点
pre = cur; // 把这一轮的当前节点作为下一轮的pre节点
cur = pos; // 把这一轮的pos节点作为下一轮的当前节点
} // 退出循环时cur为空,最后一个节点是pre逆序指向前面
slow = pre;
// slow和head同时开始走
while (slow != null && head != null) {
if (slow.value != head.value) {
reverse(pre);
return false;
}
slow = slow.next;
head = head.next;
}
reverse(pre);
return true;
}
public static Node reverse(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next; // 把下一个节点存储起来
head.next = pre; // 把当前节点的指针指向前一个节点
pre = head; // 把当前节点作为下一个节点的前一个节点
head = next; // 把刚刚存储好的下一个节点作为当前节点
}
return pre;
}
public static void printLinkedList(Node node) {
System.out.print("Linked List: ");
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = null;
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(2);
head.next.next.next.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(1);
printLinkedList(head);
System.out.print(isPalindrome1(head) + " | ");
System.out.print(isPalindrome2(head) + " | ");
System.out.println(isPalindrome3(head) + " | ");
System.out.println("Original LinkedList after isPalindrome3:");
printLinkedList(head);
System.out.println("=========================");
}
}
6、拷贝一个带random指针的链表
package sword_to_offer_linkedlist;
import java.util.HashMap;
public class CopyLinkedListWithRandomPointer {
public static class Node {
public int value;
public Node next;
public Node rand;
public Node(int value) {
this.value = value;
}
}
// 用HashMap,K-原链表,V-拷贝后的链表,空间复杂度:O(n)
public static Node copyLinkedListWithRandomPointer1(Node head) {
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
while (cur != null) {
map.put(cur, new Node(cur.value));
cur = cur.next;
}
cur = head;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).rand = map.get(cur.rand);
cur = cur.next;
}
return map.get(head);
}
// 空间复杂度:O(1)
public static Node copyLinkedListWithRandomPointer2(Node head) {
if (head == null) return null;
Node cur = head;
Node next = null;
// 将每一个的复制节点(只含值)放在该节点的后面
while (cur != null) {
next = cur.next; // 原有链表的下一个节点
cur.next = new Node(cur.value);
cur.next.next = next;
cur = next;
}
cur = head;
Node curCopy = null;
// 为每一个复制节点指定rand指针
while (cur != null) {
curCopy = cur.next;
curCopy.rand = cur.rand == null ? null : cur.rand.next;
cur = cur.next.next;
}
Node res = head.next;
cur = head;
// 分割成两个链表
while (cur != null) {
next = cur.next.next;
curCopy = cur.next;
cur.next = next;
curCopy.next = next == null ? null : next.next;
cur = cur.next;
}
return res;
}
public static void printRandLinkedList(Node head) {
Node cur = head;
System.out.print("order: ");
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
System.out.println();
cur = head;
System.out.print("rand: ");
while (cur != null) {
System.out.print(cur.rand == null ? "- " : cur.rand.value + " ");
cur = cur.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.rand = head.next.next.next.next.next; // 1 -> 6
head.next.rand = head.next.next.next.next.next; // 2 -> 6
head.next.next.rand = head.next.next.next.next; // 3 -> 5
head.next.next.next.rand = head.next.next; // 4 -> 3
head.next.next.next.next.rand = null; // 5 -> null
head.next.next.next.next.next.rand = head.next.next.next; // 6 -> 4
System.out.println("Original LinkedList:");
printRandLinkedList(head);
System.out.println("Copy LinkedList:");
Node res1 = copyLinkedListWithRandomPointer1(head);
printRandLinkedList(res1);
System.out.println("Original LinkedList After Copy");
printRandLinkedList(head);
System.out.println("=============================");
System.out.println("Original LinkedList:");
printRandLinkedList(head);
Node res2 = copyLinkedListWithRandomPointer2(head);
System.out.println("Copy LinkedList:");
printRandLinkedList(res2);
System.out.println("Original LinkedList After Copy");
printRandLinkedList(head);
}
}
7、判断一个单链表是否有环
package sword_to_offer_linkedlist;
import java.util.HashSet;
public class LinkedListHasLoopOrNot {
// 判断链表是否有环,如果有环则返回第一个入环的节点,如果无环则返回空
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
// 1、head作为key放入hashset,只有key,没有value,空间复杂度O(n)
public static Node getLoopNode1(Node head) {
if (head == null) return null;
HashSet<Node> set = new HashSet<>();
while (head != null) {
if (!set.add(head)) {
return head;
}
head = head.next;
}
return null;
}
// 2、不使用辅助空间
// 快指针一次走两步,慢指针一次走一步,如果快指针遇到空则返回无环
// 如果有环则快指针和慢指针一定会相遇,相遇后快指针回到开头,以后快指针和慢指针都一次走一步,相遇处即为入环节点
public static Node getLoopNode2(Node head) {
if (head == null) return null;
Node fast = head.next.next;
Node slow = head.next;
while (fast != slow) {
if (fast == null || fast.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = head;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
public static void main(String[] args) {
// 1->2->3->4->5->6->7->4...
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(6);
head1.next.next.next.next.next.next = new Node(7);
head1.next.next.next.next.next.next = head1.next.next.next; // 7->4
if (getLoopNode2(head1) == null) {
System.out.println("The LinkedList doesn't have loop");
} else {
System.out.println("The value of first loop node is " + getLoopNode2(head1).value);
}
// 1->2->3->4->5->6->7->null
Node head2 = new Node(1);
head2.next = new Node(2);
head2.next.next = new Node(3);
head2.next.next.next = new Node(4);
head2.next.next.next.next = new Node(5);
head2.next.next.next.next.next = new Node(6);
head2.next.next.next.next.next.next = new Node(7);
if (getLoopNode2(head2) == null) {
System.out.println("The LinkedList doesn't have loop");
} else {
System.out.println("The value of first loop node is " + getLoopNode2(head2).value);
}
}
}
8、找到两个单链表第一个相交的节点
package sword_to_offer_linkedlist;
import java.util.HashSet;
// 问题1、判断链表是否有环,如果有环则返回第一个入环的节点,如果无环则返回空
// 问题2、判断两个链表是否相交,若相交则返回相交的第一个节点,若不相交则返回null
public class FindFirstIntersectNodeBetweenTwoLinkedList {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
// 1、head作为key放入hashset,只有key,没有value,空间复杂度O(n)
public static Node getLoopNode1(Node head) {
if (head == null) return null;
HashSet<Node> set = new HashSet<>();
while (head != null) {
if (!set.add(head)) {
return head;
}
head = head.next;
}
return null;
}
// 2、O(1),准备两个指针,快指针一次走两步,慢指针一次走一步
// 如果快指针遇到空,返回无环
// 如果快指针和慢指针相遇,快指针回到开头,以后快指针和慢指针都一次走一步,快指针和慢指针会在入环节点处相遇
// 2、不使用辅助空间
// 快指针一次走两步,慢指针一次走一步,如果快指针遇到空则返回无环
// 如果有环则快指针和慢指针一定会相遇,相遇后快指针回到开头,以后快指针和慢指针都一次走一步,相遇处即为入环节点
public static Node getLoopNode2(Node head) {
if (head == null) return null;
Node fast = head.next.next;
Node slow = head.next;
while (fast != slow) {
if (fast == null || fast.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = head;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
// 找到第一个相交的节点
// 1、判断两个无环单链表是否相交:
// (1) O(n):链表一的节点都放到map里,遍历链表二,第一个在map中的节点为相交节点,如果遍历到空都没找到在map中的则不相交
// (2) O(1):先遍历链表一和链表二,统计链表一、二的长度和链表一、二的最后一个节点
// 如果end1 != end2,链表一和链表二不可能相交
// 如果end1 == end2,长度一100和长度二80比较,head1先走20步,然后head1和head2一起走,他们一定会共同走到第一个相交的节点处
// 2、一个有环一个无环的单链表,不可能相交
// 3、两个有环的单链表:三种情况
public static Node getIntersectNode(Node head1, Node head2) {
if (head1 == null || head2 == null) return null;
// loop1为链表1的入环节点
// loop2为链表2的入环节点
Node loop1 = getLoopNode2(head1);
Node loop2 = getLoopNode2(head2);
// 两个链表都无环
if (loop1 == null && loop2 == null) {
return noLoop2(head1, head2);
}
if (loop1 != null && loop2 != null) {
return bothLoop(head1, head2, loop1, loop2);
}
return null;
}
private static Node noLoop1(Node head1, Node head2) {
// 空间复杂度O(n)的方法:
// 将链表1的节点都放入HashSet中,遍历链表2,
// 找到的第一个在HashSet中存在的节点为相交节点,如果遍历到空都没在HashSet中找到则不相交
HashSet<Node> set = new HashSet<>();
while (head1 != null) {
set.add(head1);
head1 = head1.next;
}
while (head2 != null) {
if (set.contains(head2)) {
return head2;
}
head2 = head2.next;
}
return null;
}
private static Node noLoop2(Node head1, Node head2) {
// 空间复杂度O(1)的方法:
// 先遍历得到链表一和链表二的长度和最后一个节点,如果end1 != end2则不可能相交
// end1 == end2,若链表1长度为100,链表2长度为80,则head1先走20,然后head1和head2一起走,相遇处即第一个相交节点处
Node cur = head1;
int count = 0;
while (cur.next != null) {
cur = cur.next;
count++;
}
Node end1 = cur;
cur = head2;
while (cur.next != null) {
cur = cur.next;
count--;
}
Node end2 = cur;
if (end1 != end2) return null;
Node longer = count > 0 ? head1 : head2;
Node shorter = longer == head1 ? head2 : head1;
count = Math.abs(count);
while (count > 0) {
longer = longer.next;
count--;
}
while (longer != shorter) {
longer = longer.next;
shorter = shorter.next;
}
return longer;
}
private static Node bothLoop(Node head1, Node head2, Node loop1, Node loop2) {
if (loop1 == loop2) {
return bothLoopCase2(head1, head2, loop1);
}
Node cur1 = loop1;
while (cur1 != null) {
if (cur1 == loop2) {
return loop1; // case3
}
cur1 = cur1.next;
}
return null; // case1
}
// 此情况下等同于无环链表相交
private static Node bothLoopCase2(Node head1, Node head2, Node loop) {
Node cur = head1;
int count = 0;
while (cur.next != loop) {
cur = cur.next;
count++;
}
Node end1 = cur;
cur = head2;
while (cur.next != loop) {
cur = cur.next;
count--;
}
Node end2 = cur;
if (end1 != end2) return null;
Node longer = count > 0 ? head1 : head2;
Node shorter = longer == head1 ? head2 : head1;
count = Math.abs(count);
while (count > 0) {
longer = longer.next;
count--;
}
while (longer != shorter) {
longer = longer.next;
shorter = shorter.next;
}
return longer;
}
public static void main(String[] args) {
// 1->2->3->4->5->6->7->null
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(6);
head1.next.next.next.next.next.next = new Node(7);
// 0->9->8->6->7->null
Node head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next.next.next.next.next; // 8->6
System.out.println(getIntersectNode(head1, head2).value);
// 1->2->3->4->5->6->7->4...
head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(6);
head1.next.next.next.next.next.next = new Node(7);
head1.next.next.next.next.next.next = head1.next.next.next; // 7->4
// 0->9->8->2...
head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next; // 8->2
System.out.println(getIntersectNode(head1, head2).value);
// 0->9->8->6->4->5->6..
head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next.next.next.next.next; // 8->6
System.out.println(getIntersectNode(head1, head2).value);
}
}