監控系統概念
阿新 • • 發佈:2021-10-31
LeetCode、連結串列
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); }