关于链表的三个常用算法
2013-07-01 11:29
429 查看
//找到环的第一个入口点 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; }
相关文章推荐
- JAVA中关于链表的操作和基本算法
- 数据结构学习笔记 --- 线性表 (一些常见的关于链表的算法和面试题)
- 树---关于二叉树的三个小算法
- 链表常用算法
- JAVA中关于链表的操作和基本算法
- JAVA中关于链表的操作和基本算法
- 关于链表算法题的双指针
- 【常用算法思路分析系列】链表相关高频题集
- 数据结构习题分析:已知由一个线性链表表示的线性表中含有三类字符的数据元素,是编写算法将该线性表分割为三个循环链表,其中每个。。。。。
- c语言数据结构——链表常用算法
- 关于日期的常用算法
- [算法]数据结构中关于货郎担路径问题的常用解法,边界路径问题
- 关于数据库索引设计的几个常用算法
- 链表常用操作算法集合
- JAVA中关于链表的操作和基本算法
- 关于日期的常用算法
- 两个关于链表的算法
- JAVA中关于链表的操作和基本算法
- 常用算法整理:链表相关
- 关于日期的常用算法