BoggartBear
BoggartBear

Reputation: 35

How to use the LinkedList class' AddAfter method

After looking on MSDN I've found that I am supposed to have a target node for the following code:

var listOffences = new LinkedList<string>();
listOffences.AddFirst("aaa");
listOffences.AddAfter("bbb"); // Requires target node

I have no idea how to get the required information for the first node, can anyone point me in the right direction?

Upvotes: 1

Views: 5252

Answers (2)

PrinceTyke
PrinceTyke

Reputation: 213

To get the first node of a linked list, you can just used LinkedList.First.

var listOffences = new LinkedList<string>();
listOffences.AddFirst("aaa");
var firstNode = listOffences.First;
listOffences.AddAfer(firstNode, "bbb");

Alternatively, you can use the find methods to find specific values.

var listOffences = new LinkedList<string>();
listOffences.AddFirst("aaa");
listOffences.AddLast("bbb");
listOffences.AddLast("ccc");
listOffences.AddAfter(listOffences.Find("bbb"), "ddd");

A breakdown of this section:

  1. Create the LinkedList
  2. Add "aaa" first
  3. Add "bbb" onto the end of the list
  4. Add "ccc" onto the end of the list
  5. Find the node containing "bbb" and add "ddd" to the list after the "bbb" node.

Upvotes: 3

Habib
Habib

Reputation: 223307

AddFirst will return the newly added node you can use that in AddAfter

var listOffences = new LinkedList<string>();
var firstNode = listOffences.AddFirst("aaa");
// you may not need the `secondNode` returned. 
var secondNode = listOffences.AddAfter(firstNode, "bbb"); // Requires target node

or if don't need the second node reference then:

listOffences.AddAfter(firstNode, "bbb"); 

Upvotes: 8

Related Questions