1.冒泡排序
static void Swap(ref int a,ref int b)
{
a = a + b;
b = a - b;
a = a - b;
}
static void BubbleSort(int[] array)
{
if (array == null || array.Length == 0)
return;
for(int i=0;i<array.Length-1;i++)//i从0到length-1
{
for(int j= i+1;j<array.Length;j++)//j从i+1到length
{
if (array[i] > array[j])
Swap(ref array[i], ref array[j]);
}
}
}
2.二叉搜索树转双向链表
class BinaryTreeNode
{
public int Value;
public BinaryTreeNode LeftNode;
public BinaryTreeNode RightNode;
public BinaryTreeNode(int value)
{
this.Value = value;
}
}
class BinaryTree
{
public BinaryTreeNode rootNode;
public BinaryTree()
{
//rootNode = new BinaryTreeNode(5);
//rootNode.LeftNode = new BinaryTreeNode(4);
//rootNode.RightNode = new BinaryTreeNode(6);
}
public static BinaryTreeNode ConvertToList(BinaryTreeNode rootNode)
{
if (rootNode == null)
return null;
BinaryTreeNode lastNodeInList = null;
Convert(rootNode,ref lastNodeInList);
BinaryTreeNode headNodeInList = lastNodeInList;
while (headNodeInList.LeftNode != null)
headNodeInList = headNodeInList.LeftNode;
return headNodeInList;
}
private static void Convert(BinaryTreeNode CurrNode,ref BinaryTreeNode lastNodeInList)
{
if (CurrNode == null)
return;
if (CurrNode.LeftNode != null)
Convert(CurrNode.LeftNode,ref lastNodeInList);
CurrNode.LeftNode = lastNodeInList;
if (lastNodeInList != null)
lastNodeInList.RightNode = CurrNode;
lastNodeInList = CurrNode;
if (CurrNode.RightNode != null)
Convert(CurrNode.RightNode,ref lastNodeInList);
}
}
3.第一个只出现一次的字符
public static char FindFirstCharFromStr(string str)
{
if (str == null || str == "")
{
Console.WriteLine("字符串不能为空");
return '\0';
}
char[] charArray = str.ToCharArray();
int[] hashTable = new int[256];
int index = -1;
for(int i=0;i<hashTable.Length;i++)
{
hashTable[i] = 0;
}
foreach(char c in charArray)
{
hashTable[(int)c] += 1;
}
for(index=0;index<hashTable.Length;index++)
{
if (hashTable[index] == 1)
break;
}
if (index >= 256 || index == -1)
{
Console.WriteLine("字符串中不存在只出现一次的字符");
return '\0';
}
else
return (char)index;
}