关于链表的三个常用算法
来源:互联网 发布:知乎formac 编辑:程序博客网 时间:2024/06/04 19:04
//找到环的第一个入口点 static public SinglyLinkedListNode<T> FindLoopPort(SinglyLinkedList<T> list) { SinglyLinkedListNode<T> pslow = list.head; SinglyLinkedListNode<T> pfast = list.head; //为什么有环的单向链表这样做一定会相交? while (pfast != null && pfast.next != null) { pslow = pslow.next; // 每次前进一步 pfast = pfast.next.next; // 每次前进二步 if (pslow == pfast) // 两个指针相遇,说明存在环 break; } if (pfast == null || pfast.next == null) // 不存在环 return null; pslow = list.head; while (pslow != pfast) { pslow = pslow.next; // 每次前进一步 pfast = pfast.next; // 每次前进一步 } return pslow; // 返回环的入口点 } //两个无环单向链表是否相交, 若相交则求出第一个相交的节点 static public SinglyLinkedListNode<T> Intersection(SinglyLinkedList<T> list1, SinglyLinkedList<T> list2) { int len1 = list1.Count; int len2 = list2.Count; int distance=Math.Abs(len1-len2); SinglyLinkedListNode<T> head1=list1.head; SinglyLinkedListNode<T> head2=list2.head; if (len1 < len2) { for (int i = 0; i < distance; i++) head2 = head2.next; } else if (len2 < len1) { for (int i = 0; i < distance; i++) head1 = head1.next; } //指针对齐之后开始确定相交节点 while (head1.next != null && head2.next != null && head1 != head2) { head1 = head1.next; head2 = head2.next; } if (head1 != null && head2 != null) return head1; else return null; } //单向链表的反转 static public void Reverse(SinglyLinkedList<T> list) { SinglyLinkedListNode<T> p, q; SinglyLinkedListNode<T> temp; if (list.Count >= 2) { p = list.head; q = p.next; } else return; while (q != null) { temp = q.next; q.next = p; p = q; q = temp; } list.head.next = null; list.head = p; }