0
我正在用一些簡單的按鈕來填充數組/列表,然後嘗試對它們進行排序。我似乎無法得到排序權。幫助讚賞。使用雙向鏈表對數值進行排序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DoublyLinkedList1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Sortbtn_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
int[] array = new int[listBox1.Items.Count];
for (int i = 0; i < array.Length; i++)
{
array[i] = int.Parse(listBox1.Items[i].ToString());
}
array = cN.notearray(array);
for (int i = 0; i < array.Length; i++)
{
listBox2.Items.Add(array[i]);
}
}
private void filllstbtn_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Random rd = new Random();
for (int i = 0; i < 8; i++)
{
listBox1.Items.Add(rd.Next(1, 9));
}
}
}
}
類CN:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoublyLinkedList1
{
class cN
{
public int V;
public cN L;
public cN R;
private static cN[] n_array;
private static cN head = null;
public cN(cN nR, cN nL, int nV)
{
V = nV;
L = nL;
R = nR;
}
public static int[] notearray(int[] array)
{
n_array = new cN[array.Length];
//Fill array with notes
for (int i = 0; i < array.Length; i++)
{
n_array[i] = new cN(null, null, array[i]);
}
head = n_array[0];
//sort array
for (int i = 0; i < n_array.Length; i++)
{
sortnode(head, n_array[i]);
}
return array_composed();
}
private static void sortnode(cN chead, cN node)
{
if (node.V > chead.V)
{
if (chead.R != null)
{
sortnode(chead.R, node);
}
else
{
chead.R = node;
node.L = chead;
}
}
else
{
if (head == chead)
{
head = node;
node.R = chead;
chead.L = node;
}
else
{
node.R = chead;
node.L = chead.L;
chead.R = node;
chead.L = node;
}
}
}
private static int[] array_composed()
{
int[] iarr = new int[n_array.Length];
cN chead = head;
int counter = 0;
while (chead != null)
{
iarr[counter] = chead.V;
chead = chead.R;
counter++;
}
iarr[counter] = chead.V;
return iarr;
}
}
}
好像有什麼毛病我sortnode方法。它不斷循環在無限循環中,我似乎無法正常工作。