我用一些简单的按钮制作WFA,用随机数填充数组/列表,然后尝试对它们进行排序。我似乎无法正确排序。帮助赞赏。
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方法似乎有问题。它不断循环,我似乎无法正常工作。
答案 0 :(得分:0)
为了简化您想要将valuse数组转换为已排序的双链接列表的问题,我希望我能正确使用此部分。说实话,我建议你改变你的approuch。
我建议首先实现一些重要的方法,比如在列表中插入新的cN。 这是我将如何编写notearray函数:
public static int[] notearray(int[] array)
{
n_array = new cN[array.Length];
for(int i=0 ; i<array.Length ; i++)
{
n_array[i] = insertItem(array[i]);
}
}
private static cN insertItem(int value)
{
cN item = new cN(null,null,value)
int i=0;
while(n_array[i]!=null && n_array[i].V < value)
{
i++;
}
/*
remember to check special conditions like if this new item is going to be head or going
to be last item in the list or both in case of empty list
*/
item .L = n_array[i].L;
item .R = n_array[i];
n_array[i].L = item;
return item;
}
请注意,n_array实际上并未排序,因此您必须像这样迭代才能在排序条件下使用它们:
cn iterator = head;
for(...)
{
doSomthing(iterator);
iterator = iterator.R;
}