Easiest way to Rotate a List in c#

后端 未结 16 3198
鱼传尺愫
鱼传尺愫 2020-12-01 07:06

Lists say I have a list List {1,2,3,4,5}

Rotate means:

=> {2,3,4,5,1} => {3,4,5,1,2} => {4,5,1,2,3}
16条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 07:43

    List

    The simplest way (for a List) is to use:

    int first = list[0];
    list.RemoveAt(0);
    list.Add(first);
    

    Performance is nasty though - O(n).

    Array

    This is basically equivalent to the List version, but more manual:

    int first = array[0];
    Array.Copy(array, 1, array, 0, array.Length - 1);
    array[array.Length - 1] = first;
    

    LinkedList

    If you could use a LinkedList instead, that would be much simpler:

    int first = linkedList.First;
    linkedList.RemoveFirst();
    linkedList.AddLast(first);
    

    This is O(1) as each operation is constant time.

    Queue

    cadrell0's solution of using a queue is a single statement, as Dequeue removes the element and returns it:

    queue.Enqueue(queue.Dequeue());
    

    While I can't find any documentation of the performance characteristic of this, I'd expect Queue to be implemented using an array and an index as the "virtual starting point" - in which case this is another O(1) solution.

    Note that in all of these cases you'd want to check for the list being empty first. (You could deem that to be an error, or a no-op.)

提交回复
热议问题