Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Module Module1
- Sub Main()
- ' Create a new LinkedList of Integer
- ' LinkedList is a doubly-linked list, allowing elements to be efficiently added or removed from both ends or at specific positions.
- Dim numbers As New LinkedList(Of Integer)
- ' Adding elements to the LinkedList
- numbers.AddLast(2) ' AddLast adds the element to the end of the LinkedList.
- numbers.AddFirst(1) ' AddFirst adds the element to the beginning of the LinkedList.
- Console.WriteLine("Count after additions: " & numbers.Count) ' Count returns the total number of elements in the LinkedList.
- ' Adding more elements
- Dim nodeThree As LinkedListNode(Of Integer) = numbers.AddLast(3) ' Adds the value 3 to the end and returns the newly created node.
- Dim nodeFour As LinkedListNode(Of Integer) = numbers.AddLast(4) ' Adds the value 4 to the end and returns the newly created node.
- ' Inserting a node before an existing node
- numbers.AddBefore(nodeFour, 5) ' Adds the value 5 before nodeFour (which contains 4).
- ' Inserting a node after the first node
- numbers.AddAfter(numbers.First, 0) ' Adds the value 0 after the first node (which contains 1).
- ' Check if the LinkedList contains a specific value
- Console.WriteLine("Contains 3: " & numbers.Contains(3)) ' Checks if the value 3 exists in the LinkedList.
- ' Removing an element by value
- numbers.Remove(0) ' Removes the first occurrence of the value 0 from the LinkedList.
- ' Remove the first and last elements
- numbers.RemoveFirst() ' Removes the first node from the LinkedList.
- numbers.RemoveLast() ' Removes the last node from the LinkedList.
- ' Accessing the first and last nodes of the LinkedList
- Dim firstNode As LinkedListNode(Of Integer) = numbers.First ' Retrieves the first node in the LinkedList.
- Dim lastNode As LinkedListNode(Of Integer) = numbers.Last ' Retrieves the last node in the LinkedList.
- Console.WriteLine("First Node Value: " & firstNode.Value) ' Accesses the value stored in the first node.
- Console.WriteLine("Last Node Value: " & lastNode.Value) ' Accesses the value stored in the last node.
- ' Traversing the list using the Next property
- ' Start from the first node and move to the next node repeatedly until the end of the list is reached.
- Console.WriteLine("Traversing the list:")
- Dim currentNode As LinkedListNode(Of Integer) = firstNode
- While currentNode IsNot Nothing
- Console.Write(currentNode.Value & " ") ' Print the value of the current node.
- currentNode = currentNode.Next ' Move to the next node in the list.
- End While
- Console.WriteLine()
- ' Final output of the LinkedList using a For Each loop
- ' The For Each loop iterates through all the values in the LinkedList.
- Console.WriteLine("Final State of LinkedList:")
- For Each num In numbers
- Console.WriteLine(num) ' Print each value in the LinkedList.
- Next
- End Sub
- End Module
Advertisement
Add Comment
Please, Sign In to add comment