今、スタック・キューアルゴリズムを実装しています。
http://flute.u-shizuoka-ken.ac.jp/~s-okubo/class/language/t006.htm
スタックとキューが実現できるようにC#で実装しているのですが、
C#
1 class MainClass 2 { 3 public static void Main (string[] args) 4 { 5 Console.WriteLine ("Hello World!"); 6 List<int> a = new List<int> (); 7 List<double> b = new List<double> (); 8 a.Add (10); 9 a.Add (20); 10 a.Add (30); 11 b.Add (40); 12// Stack stk = new Stack (); 13// stk.Push (); 14// stk.Pop (); 15 for (int i = 0; i < a.Length; i++) { 16 Console.WriteLine (a.Get(i)); 17 } 18 } 19 } 20 21 22 23 class List<T> 24 { 25 public T[] a; 26 public int Length; 27 28 public List() 29 { 30 Length = 0; 31 a = new T[0]; 32 } 33 34 35 public void Add(T v){ 36 T[] b = new T[a.Length+1]; 37 for (int i = 0; i < a.Length; i++) { 38 b[i] = a[i]; 39 } 40 b [a.Length] = v; 41 a = b; 42 Length = b.Length; 43 } 44 45 public T Get(int i){ 46 return a[i]; 47 } 48 49 public void Delete(T v){ 50 T[] c = new T[a.Length-1]; 51 for (int i = 0; i < a.Length; i++) { 52 c[i] = a[i]; 53 } 54 c [a.Length] = v; 55 a = c; 56 Length = c.Length; 57 } 58 59 60 class Stack 61 { List<int> y = new List<int> (); 62 T[] b = new T[y.Length+1]; 63 int head = y [0]; 64 int tail = y[y.Length+1]; 65 public Stack() 66 { 67 68 } 69 70 public void Push(int i){ 71 for (int x = 0; x < a.Length; x++){ 72 b.Add(i); 73 } 74 } 75 public void Pop(int i){ 76 for (int x = 0; x < a.Length; x++){ 77 b.Delete (i); 78 } 79 } 80 81 } 82 83 class Queue 84 { 85 public Queue() 86 { 87 } 88 public void Push(int i){ 89 List<int> z = new List<int> (); 90 z.Add (i); 91 z.Delete (i); 92 } 93 } 94 95 } 96 97}
2箇所エラーが出てしまいました。
一つ目が、
A field initializer cannot reference the nonstatic field, method, or property
というものです。
調べてみると、
インスタンス フィールドを使用して、メソッドの外部にある他のインスタンス フィールドを初期化することはできません。
とありましてhttps://msdn.microsoft.com/ja-jp/library/5724t6za.aspx、
”フィールドの初期化”の意味がわからず困っています。
T[] b = new T[y.Length+1]; int head = y [0]; int tail = y[y.Length+1];
ここの3行でエラーが出ました。
2つ目は、
Cannot access a non-static member of outer type というエラーです。
public void Push(int i){ for (int x = 0; x < a.Length; x++){ b.Add(i); } } public void Pop(int i){ for (int x = 0; x < a.Length; x++){ b.Delete (i); } }
のところで出て、
AddとDeleteメソットのところに
public static void Add(T v) とstaticをつけたのですが
そうすると大量にエラーが出てしまいました。
どのように書けばスタック・キューアルゴリズムができるのでしょうか?
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。