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);
}
posted @ 2021-11-04 18:33  wesson2019  阅读(24)  评论(0编辑  收藏  举报