LinkedList – a class module to store list of values

LinkedList – a class module to store list of values

'-------------------------------------------------' LINKED LIST class module'' This class implements a linked list structure, where you can store' values (appending them after the last element or inserting them at' given indexes), remove them, and visit them using recordset-like' methods such as MoveFirst, MoveNext, and Move(n)'' NOTE: make Item the default member for this class'       you can do so from inside the Tools | Procedure Attributes dialog box'' Usage:'   Dim ll As New LinkedList'   ' optionally size the inner array'   ll.SetSize 10000'   ' add new elements (can optionally take Before or After element)'   ' returns the index where the element has been stored'   newIndex = ll.Add newValue''   ' loop over all elements'   ll.MoveFirst'   Do Until ll.EOL'       ' display or process the current element'       Print ll.Item'       ' move to next element'   Loop''   See remarks for the FIND method for details about performing searches'   on the elements in the linked list''-------------------------------------------------Option Explicit' these are used by the Find methodPublic Enum FindConditionConstants    fccEqual    fccNotEqual    fccLess    fccLessEqual    fccGreater    fccGreaterEqual    fccInStrEnd Enum' initial size of the listConst DEFAULT_INITIALSIZE = 100' how many items are allocated each timeConst DEFAULT_CHUNKSIZE = 100Private Type ListType    Value As Variant    prevNdx As Long    ' -1 if the element is free    nextNdx As LongEnd Type' the actual listDim List() As ListType' number of items in the listDim m_Count As Long' index of first/last item in the listPrivate FirstNdx As LongPrivate LastNdx As Long' index of first free item in the listPrivate FreeNdx As Long' chucnk sizePrivate m_ChunkSize As Long' index to the current elementPrivate m_CurrIndex As Long' current EOL status of the list' (is valid only when m_CurrIndex = 0)Private m_EOL As Boolean     ' if False, then BOL is true' the index of the current elementProperty Get CurrIndex() As Long    CurrIndex = m_CurrIndexEnd PropertyProperty Let CurrIndex(ByVal newValue As Long)    m_CurrIndex = newValueEnd Property' move to the first elementSub MoveFirst()    m_CurrIndex = FirstNdxEnd Sub' move to the last elementSub MoveLast()    m_CurrIndex = LastNdxEnd Sub' move the the previous elementSub MovePrevious()    ' this code works also when m_CurrIndex = 0    m_CurrIndex = List(m_CurrIndex).prevNdx    ' in case we move too much    m_EOL = FalseEnd Sub' move to the next elementSub MoveNext()    ' this code works also when m_CurrIndex = 0    m_CurrIndex = List(m_CurrIndex).nextNdx    ' in case we move too much    m_EOL = TrueEnd Sub' move to the Nth elementSub Move(ByVal Index As Long)    CheckIndex Index    ' if there were no error, then update the current Index    m_CurrIndex = IndexEnd Sub' Return true if we are at the beginning of listProperty Get BOL() As Boolean    BOL = (m_Count = 0) Or (m_CurrIndex = 0 And m_EOL = False)End Property' Return true if we are at the end of listProperty Get EOL() As Boolean    EOL = (m_Count = 0) Or (m_CurrIndex = 0 And m_EOL = True)End Property' An item of the list (read-write)' if the argument is omitted it retrieves the current itemProperty Get Item(Optional ByVal Index As Long) As VariantAttribute Item.VB_UserMemId = 0    If Index = 0 Then Index = m_CurrIndex    ' check that the index point to a valid, non-free element    CheckIndex Index    ' two cases: the value is/isn't an object    If IsObject(List(Index).Value) Then        Set Item = List(Index).Value    Else        Item = List(Index).Value    End IfEnd PropertyProperty Let Item(Optional ByVal Index As Long, newValue As Variant)    If Index = 0 Then Index = m_CurrIndex    ' check that this is a valid, non-free item    CheckIndex Index    ' modify the value in the list    List(Index).Value = newValueEnd PropertyProperty Set Item(Optional ByVal Index As Long, newValue As Object)    If Index = 0 Then Index = m_CurrIndex    ' check that this is a valid, non-free item    CheckIndex Index    ' modify the value in the list    Set List(Index).Value = newValueEnd Property' return True if the list is emptyProperty Get IsEmpty() As Boolean    IsEmpty = (m_Count = 0)End Property' the number of elements in the listProperty Get Count() As Long    Count = m_CountEnd Property' insert a new item before/after a given element' if both arguments are omitted it is appended to the end of the list' a zero or negative value for Before means "at the beginning of the list"' and works also when the list is empty'' returns the index of the new valueFunction Add(Value As Variant, Optional ByVal Before As Long, _    Optional ByVal After As Long) As Long    Dim ndx As Long    Dim nextFreeNdx As Long        ' enlarge the list if necessary    If FreeNdx = 0 Then ExpandList m_ChunkSize    ' use the first free slot    ndx = FreeNdx    nextFreeNdx = List(ndx).nextNdx        ' a special value for Before that means "at the beginning of the list"    If Before < 0 Then Before = FirstNdx        If Before > 0 Then        ' check that this is a valid, non-free item        CheckIndex Before        ' "Before" item becomes this item's next element        List(ndx).nextNdx = Before        ' "Before"'s previous element becomes this item's previous element        List(ndx).prevNdx = List(Before).prevNdx        ' "Before's" previous element should point to this item        List(Before).prevNdx = ndx                If Before = FirstNdx Then            ' "Before" was the first item in the list            FirstNdx = ndx        Else            ' else, another item's next element points to this item            List(List(ndx).prevNdx).nextNdx = ndx        End If        ElseIf After > 0 Then        ' check that this is a valid, non-free item        CheckIndex After        ' "After" item becomes this item's previous element        List(ndx).prevNdx = After        ' "After" item's next element becomes this item's next element        List(ndx).nextNdx = List(After).nextNdx        ' "After"'s next element should point to this item        List(After).nextNdx = ndx                If After = LastNdx Then            ' "After" was the last item in the list            LastNdx = ndx        Else            ' else, another item's previous element points to this item            List(List(ndx).nextNdx).prevNdx = ndx        End If            Else        ' append at the end of the list        If LastNdx Then            ' this item becomes the "next" item of the            ' item that was at the end of the list            List(LastNdx).nextNdx = ndx            List(ndx).prevNdx = LastNdx        Else            ' this is the first and only item in the list            FirstNdx = ndx            ' signal that this item isn't free any longer            List(ndx).prevNdx = 0        End If        ' in all cases this becomes the last item in the list        LastNdx = ndx        List(ndx).nextNdx = 0    End If        ' actually store the new value    If IsObject(Value) Then        Set List(ndx).Value = Value    Else        List(ndx).Value = Value    End If    ' remember we have a new item    m_Count = m_Count + 1    ' FreeNdx must point to the first free slot    FreeNdx = nextFreeNdx        ' return the index of the element just added    Add = ndx    End Function' remove an item given its index' if the index is omitted it removes the current item'' if the item is also the current item, then its subsequent' element becomes the current item (if it was the last element' then the EOL condition becomes True)Sub Remove(Optional ByVal Index As Long)    If Index = 0 Then Index = m_CurrIndex    ' check that this is a valid, non-free item    CheckIndex Index        If Index = FirstNdx Then        ' the item being removed is the first of the list        FirstNdx = List(Index).nextNdx        List(FirstNdx).prevNdx = 0    ElseIf Index = LastNdx Then        ' the item being removed is the last of the list        ' but the list contains at least another item        LastNdx = List(Index).prevNdx        List(LastNdx).nextNdx = 0    Else        ' the item is in the middle of the list        List(List(Index).prevNdx).nextNdx = List(Index).nextNdx        List(List(Index).nextNdx).prevNdx = List(Index).prevNdx    End If    ' clear this item's value    List(Index).Value = Empty    ' remember we have one element less    m_Count = m_Count - 1        ' if this was the current item, update m_CurrIndex    If Index = m_CurrIndex Then        m_CurrIndex = List(Index).nextNdx        ' if it was the last element of the list        If m_CurrIndex = 0 Then m_EOL = True    End If    ' put it at the beginning of the free list    List(Index).nextNdx = FreeNdx    ' mark it as free    List(Index).prevNdx = -1    FreeNdx = IndexEnd Sub' remove all items' this method also resets any SetSize settingSub RemoveAll()    ' it simply restarts from the very beginning    Class_InitializeEnd Sub' search a value in the list'' STARTINDEX is the index of the element from where to' start the search - use ZERO or omitted to start from' the current element, use -1 to start from first/last element' if DESCENDING is True then it does a reverse search'' returns the index of the found element, or zero if not found' the element also becomes the current elementFunction Find(Value As Variant, Optional Condition As FindConditionConstants = _    fccEqual, Optional ByVal StartIndex As Long, Optional ByVal Descending As _    Boolean) As Long    Dim isObj As Boolean        ' provide reasonable defaults    If StartIndex = 0 Then        StartIndex = m_CurrIndex    ElseIf StartIndex < 0 Then        If Not Descending Then            StartIndex = FirstNdx        Else            StartIndex = LastNdx        End If    Else        ' check that this index is valid        CheckIndex StartIndex        ' start from the next or previous element        If Not Descending Then            StartIndex = List(StartIndex).nextNdx        Else            StartIndex = List(StartIndex).prevNdx        End If    End If        ' evaluate this once and for all    isObj = IsObject(Value)        ' two loops, depending on value being an object or not    Do While StartIndex        If isObj Then            ' do the comparison only if the element is also an object            If IsObject(List(StartIndex).Value) Then                If Value Is List(StartIndex).Value Then                    ' exit if we're looking for equality                    If Condition <> fccNotEqual Then Exit Do                Else                    ' exit if we're looking for inequality                    If Condition = fccNotEqual Then Exit Do                End If            End If        Else            ' do the comparison only if the element isn't an object            If Not IsObject(List(StartIndex).Value) Then                Select Case Condition                    Case fccNotEqual                        If List(StartIndex).Value <> Value Then Exit Do                    Case fccLess                        If List(StartIndex).Value < Value Then Exit Do                    Case fccLessEqual                        If List(StartIndex).Value <= Value Then Exit Do                    Case fccGreater                        If List(StartIndex).Value > Value Then Exit Do                    Case fccGreaterEqual                        If List(StartIndex).Value >= Value Then Exit Do                    Case fccInStr                        If InStr(List(StartIndex).Value, Value) Then Exit Do                    Case Else                        ' equality is the default test                        If List(StartIndex).Value = Value Then Exit Do                End Select            End If        End If        ' skip to the next or previous item        If Not Descending Then            StartIndex = List(StartIndex).nextNdx        Else            StartIndex = List(StartIndex).prevNdx        End If    Loop            ' make the item the current item and return its index    m_CurrIndex = StartIndex    Find = StartIndex        End Function' modify the list size and growth factor' you can expand but not shrink a linked listSub SetSize(ByVal numEls As Long, Optional ByVal ChunkSize As Long)    ' raise an error if invalid arguments    If numEls <= 0 Or ChunkSize < 0 Then Err.Raise 5        If numEls > UBound(List) Then        ' expand the list        ExpandList numEls - UBound(List)    End If    ' remember new ChunkSize    m_ChunkSize = ChunkSizeEnd Sub'--------------------------------------------' Private procedures'--------------------------------------------Private Sub Class_Initialize()    ' initialize the linked list of free slots    ReDim List(0) As ListType    ExpandList DEFAULT_INITIALSIZE    m_ChunkSize = DEFAULT_CHUNKSIZEEnd Sub' check that there is at least one free slotPrivate Sub ExpandList(ByVal numEls As Long)    Dim ndx As Long, newFreeNdx As Long        ' this will be the first free slot    newFreeNdx = UBound(List) + 1    ' expand the list    ReDim Preserve List(UBound(List) + numEls) As ListType    ' initialize the links for free items    ' (note that the nextNdx value for the last element isn't correct    For ndx = newFreeNdx To UBound(List)        List(ndx).nextNdx = ndx + 1        List(ndx).prevNdx = -1    Next    ' append the existing chain of free slots    ' (fixes the invalid value stored previously)    List(UBound(List)).nextNdx = FreeNdx    ' this is the new start of the free list    FreeNdx = newFreeNdxEnd Sub' check whether an index is validSub CheckIndex(ByVal Index As Long)    If Index <= 0 Or Index > UBound(List) Then Err.Raise 5    If List(Index).prevNdx < 0 Then Err.Raise 5End Sub

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists