Удаление элемента из односвязного списка - C#
Формулировка задачи:
Доброе утро. Никак не могу реализовать удаление элемента из списка. Получается только после найденного элемента.
В объекте, который в список засовывается есть указатель только на следующий элемент. Я так понимаю, надо прям в этой функции как-то организовать указатель на предыдущий элемент и менять адресные связи. Хз уже, как это сделать.
public void Delete(PageRam page)
{
PageRam temp = Search(page); // Находим элемент, Который надо удалить
PageRam d;
if (temp != null)
{
d = temp.Next;
temp.Next = d.Next;
d = null;
}
}Решение задачи: «Удаление элемента из односвязного списка»
textual
Листинг программы
using System;
using System.Collections.Generic;
namespace A
{
class Program
{
public class TruList<A>
{
public TruList<A> next {get;set;}
public A value { get; set; }
public TruList() { }
public TruList(A x, TruList<A> n) { value = x; next = n; }
}
static private TruList<A> truList<A>(A x, TruList<A> n) { return new TruList<A>(x, n); }
static private void print<A>(TruList<A> xs) {
while (xs != null) { Console.Write("{0} ", xs.value); xs = xs.next; }
Console.WriteLine();
}
static private TruList<A> remove<A>(TruList<A> xs, A x) where A: struct
{
TruList<A> prev = null;
TruList<A> scan = xs;
while (scan != null)
{
if (scan.value.Equals(x))
{
if (prev == null) { xs = scan.next; scan.next = null; }
else { prev.next = scan.next; scan.next = null; }
break;
}
else
{
prev = scan;
scan = scan.next;
}
}
return xs;
}
static void Main(string[] args)
{
var list = truList(1, truList(2, truList(3, truList(7, truList(4, truList(5, null))))));
print(list);
list = remove(list, 3);
print(list);
list = remove(list, 1);
print(list);
list = remove(list, 5);
print(list);
list = remove(list, 7);
print(list);
Console.ReadKey();
}
}
}