二维数组中元素怎么移动
如图所示 二维数组中存放若干字符串现在要求把数组中元素为null的移动到每一列的最上端
构成如下图所示的二维数组
应该怎么移动呢?
[解决办法]
我用 链表
第一步, 循环 列长 (列长为3)
第二步, 取出这列所有元素 放到 链条表里
第三步, 遍历链表, 如果当前元素为null 就放到头部,其余接起来
第四步, 放回 源 数组中
[解决办法]
- C# code
string[][] test_array = new string[4][] { new string[]{"aaa","ddd","fff"}, new string[]{"bbb",null,"ggg"}, new string[]{null,null,"hhh"}, new string[]{"ccc","eee","iii"} }; for (int k = 0; k < test_array.Count() - 1; k++) { for (int i = 0; i < test_array.FirstOrDefault().Count(); i++) { for (int j = test_array.Count() - 1; j > 0; j--) { if (string.IsNullOrEmpty(test_array[j][i]) && !string.IsNullOrEmpty(test_array[j - 1][i])) { string temp = test_array[j][i]; test_array[j][i] = test_array[j - 1][i]; test_array[j - 1][i] = temp; } } } } for (int i = 0; i < test_array.Count(); i++) { for (int j = 0; j < test_array[i].Count(); j++) { Console.Write(test_array[i][j]+"\t"); } Console.Write("\n"); }