zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    ⑬linux基础命令 wget
    爱情的诗·21~25节
    爱情的诗·16~20节
    爱情的诗·11~15节
    人生的诗·406~410节
    唐诗宋词学习·126~130节
    爱情的诗·6~10节
    人生的诗·401~405节
    唐诗宋词学习·121~125节
    唐诗宋词学习·100~105节
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/15509599.html
Copyright © 2011-2022 走看看