Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to Rotate a List in c#

Tags:

arrays

c#

list

linq

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

Rotate means:

=> {2,3,4,5,1} => {3,4,5,1,2} => {4,5,1,2,3} 

Maybe rotate is not the best word for this, but hope you understand what I means

My question, whats the easiest way (in short code, c# 4 Linq ready), and will not be hit by performance (reasonable performance)

Thanks.

like image 984
Eric Yin Avatar asked Mar 30 '12 18:03

Eric Yin


People also ask

How do you rotate a linked list?

To rotate the linked list, we need to change the next pointer of kth node to NULL, the next pointer of the last node should point to previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node.

How do you rotate a list in C#?

The simplest way (for a List<T> ) is to use: int first = list[0]; list. RemoveAt(0); list. Add(first);

Which algorithm is best for array rotation?

The block swap algorithm for array rotation is an efficient algorithm that is used for array rotation. It can do your work in O(n) time complexity. So, in array rotation, we are given an array arr[] of size n and a number k that define the no.

How do you rotate an array?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.


2 Answers

List<T>

The simplest way (for a List<T>) 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<T> version, but more manual:

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

LinkedList<T>

If you could use a LinkedList<T> 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<T>

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<T> 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.)

like image 91
Jon Skeet Avatar answered Sep 20 '22 00:09

Jon Skeet


You could implement it as a queue. Dequeue and Enqueue the same value.

**I wasn't sure about performance in converting a List to a Queue, but people upvoted my comment, so I'm posting this as an answer.

like image 35
cadrell0 Avatar answered Sep 21 '22 00:09

cadrell0