最近在研究单链表相交的问题时,为验证思路的正确性,使用java简单实现了单链表,包括增删改查和判断是否有环及解环、成环等方法。
public class Node {
private int value = -1;
private Node next;
Node(int value) {
this.value = value;
}
public static Node getRing(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static Node deRing(Node head) {
Node ringNode = getRing(head);
if (ringNode == null) {
return null;
}
Node p = ringNode;
while (p.next != ringNode) {
p = p.next;
}
p.next = null;
return ringNode;
}
public static void reRing(Node head) {
tail(head).next = head;
}
static Node tail(Node head) {
Node p = head;
while (p.next != null) {
p = p.next;
}
return p;
}
public static Node crossing(Node A, Node B) {
Node ringA = deRing(A);
Node ringB = deRing(B);
Node tailA = tail(A);
reRing(A);
Node crossing = getRing(B);
tailA.next = ringA;
tail(B).next = ringB;
return crossing;
}
void add(int value) {
tail(this).next = new Node(value);
}
void add(Node p) {
tail(this).next = p;
}
int val() {
return this.value;
}
Node get(int n) {
Node p = this;
while (n > 0) {
p = p.next;
n--;
}
return p;
}
void set(int value) {
this.value = value;
}
void delete(Node n) {
Node p = this;
while (p.next != n) {
p = p.next;
}
p.next = n.next;
}
}
文章内容皆原创,转载请注明作者。