• 24. Swap Nodes in Pairs


    SLinkedList<int> slist = new SLinkedList<int>();
    slist.AppendRange(new[] { 1, 2, 3, 4 });
    Console.WriteLine("Input: " + slist.Print());
    var rslt = slist.SwapPairs();
    Console.WriteLine("Output:" + rslt.Print());
    

    /// <summary>
    /// 两两相邻的元素,翻转链表
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    /// <returns></returns>
    public static SLinkedList<T> SwapPairs<T>(this SLinkedList<T> source) where T : IComparable<T>
    {
        if (source.Head == null || source.Head.Next == null)
        {
            return source;
        }
        var tmp = new SLinkedList<T>(source);
        var head = tmp.Head;
        var node = head.Next;
        var behind = new SLinkedListNode<T>();
        while (head.Next != null)
        {
            var headNext = head.Next;
            if (behind != null && behind.Next != null)
            {
                behind.Next = headNext;
            }
            var next = new SLinkedListNode<T>();
            if (head.Next.Next != null)
            {
                next = head.Next.Next;
            }
            if (head.Next.Next != null)
            {
                head.Next = next;
            }
            else
            {
                head.Next = null;
            }
            headNext.Next = head;
            behind = head;
            if (head.Next != null)
            {
                head = next;
            }
        }
        return new SLinkedList<T>(node);
    }
    
  • 相关阅读:
    存储器多级结构
    649. Dota2 参议院
    pycharm安装第三方库失败
    python -m pip install --upgrade pip升级失败
    P1149 火柴棒等式
    HTTP详解
    ref与out
    EF查询数据库框架的搭建
    EF查询数据库框架的搭建
    css清除浮动
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/15509599.html
Copyright © 2020-2023  润新知