練習題 (14):Adding/removing items in the beginning, middle and end of the array.
這一題我使用泛型 List 類別來實作,利用 Add、Insert 方法來將原宿放置在各位置;利用 RemoveAt 方法來移除特定位置的元素。
程式碼:
-
using System;
-
using System.Collections.Generic;
-
namespace ListTest
-
{
-
internal class Program
-
{
-
public static void printAll(List<int> l)
-
{
-
foreach ( int i in l)
-
{
-
Console.Write ( "{0} ", i);
-
}
-
Console.WriteLine ( );
-
}
-
private static void Main( string [ ] args)
-
{
-
List<int> l = new List<int> ( );
-
l.Add ( 1 );
-
l.Add ( 2 );
-
l.Add ( 3 );
-
l.Add ( 5 );
-
l.Add ( 6 );
-
l.Add ( 7 );
-
l.Add ( 8 );
-
printAll(l);
-
// Add items in the beginning
-
l.Insert ( 0, 0 );
-
printAll(l);
-
// Add items in the middle
-
l.Insert ( 4, 4 );
-
printAll(l);
-
// Add items in the end
-
l.Add ( 9 );
-
printAll(l);
-
// remove items in the beginning
-
l.RemoveAt ( 0 );
-
printAll(l);
-
// remove items in the middle
-
l.RemoveAt ( 3 );
-
printAll(l);
-
// remove items in the end
-
l.RemoveAt (l.Count - 1 );
-
printAll(l);
-
printAll(l);
-
}
-
}
-
}
|