C#用数组模拟链表

xiaoxiao2025-04-27  10

public class SimulationList { private int[] data = new int[31]; private int[] right = new int[31]; //清除链表 public void Clear () { int i = 0; foreach (int n in data) { data[i] = 0; right[i] = 0; ++i; } } //显示链表 public void ShowList () { if (GetLength () != 0) { Console.WriteLine ("链表的长度为: {0}", GetLength ()); int i = 0; while (right[i] != 0) { Console.WriteLine (data[right[i]]); ++i; } } } //获取长度 public int GetLength () { int j = 0; foreach (int i in right) { if (i != 0) { ++j; } } if (j == 0) { return 0; } return j; } //在链表尾部添加数据 public void AddEnd (int tump) { if (GetLength () == 0) { data[1] = tump; right[0] = 1; } else { data[GetLength () + 1] = tump; int i = 0; while (right[i] != 0) { ++i; } right[i] = ++i; } } //指定位置后插入数据 public void InsertPost (int tump, int pos) { if (pos >= 1 && pos <= GetLength ()) { if (pos == GetLength ()) { data[GetLength () + 1] = tump; right[pos] = GetLength () + 1; } else { data[GetLength () + 1] = tump; for (int i = GetLength () + 1; i >= pos; i--) { if (i != pos) { right[i] = right[i - 1]; } else { right[i] = GetLength (); } } } } } //指定位置前插入数据 public void Insert (int tump, int pos) { if (pos >= 1 && pos <= GetLength ()) { if (pos == 1) { data[GetLength () + 1] = tump; for (int i = GetLength () + 1; i > 0; i--) { right[i] = right[i - 1]; } right[0] = GetLength (); } else { data[GetLength () + 1] = tump; for (int i = GetLength () + 1; i >= pos; i--) { if (i != pos) { right[i] = right[i - 1]; } else { right[i] = right[i - 1]; right[i - 1] = GetLength (); } } } } } //删除指定位置的数据 public void DeleteData (int pos) { if (pos > 0 && pos <= GetLength ()) { if (pos == GetLength ()) { right[pos - 1] = 0; return; } else { for (int i = pos - 1; i < GetLength () - 1; i++) { right[i] = right[i + 1]; } right[GetLength () - 1] = 0; } } } //获取指定位置的数据 public int GetData (int pos) { int i = 0; if (pos <= GetLength () && pos > 0) { if (pos == 1) { return data[1]; } else { while (i < pos - 1) { ++i; } return data[right[i]]; } } return -1; } //获取数据的位置 public int GetDataPos (int tump) { int i = 1; if (data[1] == tump) { return i; } else { while (right[i] != 0 && i < GetLength ()) { if (data[right[i]] != tump) { ++i; } else { return ++i; } } Console.WriteLine ("数据错误!"); return -1; } } //检查为空 public bool IsEmpty () { if (GetLength () == 0) { return true; } return false; } //冒泡排序 public void Sequence () { for (int i = 0; i < GetLength () - 1; i++) { for (int j = 0; j < GetLength () - 1; j++) { if (data[right[j]] >= data[right[j + 1]]) { int n = data[right[j]]; data[right[j]] = data[right[j + 1]]; data[right[j + 1]] = n; } } } } }

 

转载请注明原文地址: https://www.6miu.com/read-5029249.html

最新回复(0)