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);
    }
    
  • 相关阅读:
    java容器01--初遇
    java虚拟机(1)--运行时数据区
    java虚拟机(2)--垃圾收集
    java虚拟机(3)--内存分配与回收策略
    java虚拟机(4)--类加载机制
    bash编程的信号捕获:
    awk纯干货
    shell中各种括号的作用()、(())、[]、[[]]、{}
    find
    awk
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/15509599.html
Copyright © 2011-2022 走看看