Tim Kathete Stadler
Tim Kathete Stadler

Reputation: 1069

How to get the index of an element in a singly linked list?

I have two classes:

SLList for methods (private SLElement _root)

SLElement for creating new elements for the list. (public int _value; public SLElement _next)

I have finished the add-method:

public void Add(int value)
{
  SLElement addNewElement = new SLElement();
  addNewElement._value = value;
  SLElement rootCopy = _root;
  _root = addNewElement;
  addNewElement._next = rootCopy;
  Console.WriteLine(addNewElement._value);
}

So now I want a remove-function. I already got it working that it removes an element with a specific value, but I want it so that it removes an element with an specific index. How can I find out the index of the elements in my list?

Upvotes: 0

Views: 2939

Answers (3)

ajp
ajp

Reputation: 1490

Loop throw index times and find the element

public SLElement Remove(int index)
{
    SLElement prev = _root;
    if(prev == null) return null; //or throw exception
    SLElement curr = _root.next;
    for(int i = 1; i < index; i++)
    {
      if(curr == null) return null; //or throw exception
      prev = curr;
      curr = curr.next;
    }
    prev.next = curr.next; //set the previous's node point to current's next node
    curr.next = null;
    return curr;
}

Upvotes: 1

Alex Filipovici
Alex Filipovici

Reputation: 32561

Unless you have a strong reason for which you would like to create your own, I believe you should go for a LinkedList

var list = new LinkedList<SLElement>();

list.AddAfter(list.AddFirst(new SLElement()), new SLElement());

list.Remove(list.Select((i, j) => new { i, j })
    .Where(j => j.j == 0)//remove the first node
    .Select(i => i.i)
    .FirstOrDefault());

Upvotes: 2

spender
spender

Reputation: 120470

You need traverse your list from its head, counting along the way.

Upvotes: 4

Related Questions