关于链表的三个常用算法

 //找到环的第一个入口点
        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;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值