Двусвязный циклический список - C#
Формулировка задачи:
Вводятся элементы двусвязного циклического списка - числа, при добавлении в список положительные вставляются в начало, отрицательные - в конец. Нужно разделить исходный список на два так, чтобы в исходном остались положительные, а отрицательные вставились во второй.
//Удаляет отрицательные элементы, возвращает ссылку на первый отрицательный элемент
public DoubleNode DeleteNegative()
{
DoubleNode n;
DoubleNode h;
n = head.Next;
while ((n!=head)&&(n.Next.Number>0))
{
n = n.Next;
}
h = n.Next;
head.Prev=n;
n.Next = head;
return h;
}
public void GetSecondList(DoubleNode n, DoubleNode q)
{
head.Next = n;
n.Prev=head;
q.Next = head;
head.Prev = q;
}
//класс формы
private void разделитьToolStripMenuItem_Click(object sender, EventArgs e)
{
DoubleNode n = Data.L.DeleteNegative();
DoubleNode q = Data.L.FindEnd;
Data.L2.GetSecondList(n,q);
}Решение задачи: «Двусвязный циклический список»
textual
Листинг программы
class CycleDoubleLinkedList
{
private DoubleNode head;
public DoubleNode Head
{
get { return head; }
set { head = value; }
}
public CycleDoubleLinkedList()
{
head = new DoubleNode();
head.Next = head;
head.Prev = head;
}
//вставка в начало
public void InsertAfter(DoubleNode p, int number)
{
if (p != null)
{
DoubleNode q = new DoubleNode(number);
q.Next = p.Next;
p.Next = q;
q.Prev = p;
q.Next.Prev = q;
}
}
//вставка в конец
public void InsertBefore(int number)
{
InsertAfter(head, number);
}
public int Length()
{
int i = 0;
DoubleNode p = head.Next;
while (p != head) { i++; p = p.Next; }
return i;
}
public DoubleNode Return1()
{
DoubleNode p = head.Next;
return p;
}
public DoubleNode ReturnHead()
{
DoubleNode p = head;
return p;
}
public DoubleNode find1(int pos)
{
DoubleNode p = head.Next;
int i = 0;
while ((i < pos) && (p != null))
{
p = p.Next;
i++;
}
if (i != pos) throw new Exception();
return p;
}
public string get(int i)
{
DoubleNode temp = find1(i);
string s;
s = temp.Number + " ";
return s;
}
public DoubleNode FindEnd
{
get
{
DoubleNode p;
p = head;
while ((p != null) && (p.Next != head))
{
p = p.Next;
}
return p;
}
}
public void Delete(DoubleNode p)
{
if (p != null)
{
p.Prev.Next = p.Next;
p.Next.Prev = p.Prev;
p = null;
}
}
public void remove1(int pos)
{
Delete(find1(pos));
}
public string printnumber(int i)
{
DoubleNode temp = find1(i);
string s;
s = temp.Number + " ";
return s;
}
//Удаляет отрицательные элементы, возвращает ссылку на первый отрицательный элемент
public DoubleNode DeleteNegative()
{
DoubleNode n;
DoubleNode h;
n = head.Next;
while ((n!=head)&&(n.Next.Number>0))
{
n = n.Next;
}
h = n.Next.Next;
head.Prev=n;
n.Next = head;
return h;
}
public void GetSecondList(DoubleNode n, DoubleNode q)
{
head.Next = n;
n.Prev=head;
q.Next = head;
head.Prev = q;
}
}