链表——PowerShell版
鏈表是由一系列節點串連起來組成的,每一個節點包括數值部分和指針部分,上一節點的指針部分指向下一節點的數值部分所在的位置。
在C語言中我們有兩種方式來定義鏈表——
1、定義結構體:來表示鏈表中的節點,節點中包含數值部分和指針部分。將一個節點的指針部分指向另一個節點的數值部分,這兩個結構體之間就形成了一個鏈表。
2、不定義結構體:用一個數組來表示鏈表的數值部分,用另外一個數組來表示每個數值所對應的指針部分。
在PowerShell中定義一個鏈表更加簡潔:
$linkedList = New-Object System.Collections.Generic.LinkedList[HashTable]其中HashTable相當于我們在C語言中定義的結構體中的數值部分,而對于鏈表中數值進行的操作都被封裝成了一系列鏈表對象的方法。
現在我們舉一個現實生活中的例子——
考試結束,老師排好了一個成績單(按成績從高到低),現在來了個插班生,我們要把這個插班生的考試成績插入到本班的成績單中。
首先我們寫一個方法,將排好的成績單錄入到一個鏈表中:
#Initial the students' scores. function Initial($linkedList){$count = Read-Host "Type in the students' number"For($i=1; $i -le [int]$count; $i++){$tip = "This is the NO."+$i+" student"Write-Host $tip -ForegroundColor green$name = Read-Host "Type in the name"$score = Read-Host "Typen in the score"$linkedList.AddLast(@{Name=$name;Score=[int]$score}) } }然后我們寫一個方法,將插班生的成績插入到已排好序的成績單鏈表中:
#Add student into the list by score. function InsertStudent($linkedList) {$score = Read-Host "Type in the score of the student"$score = [int]$score$currentNode = $linkedList.First$flag = $truewhile(($currentNode -ne $null) -and ($flag -eq $true)){if($currentNode.Value.Score -ge $score){$currentNode = $currentNode.Next}else{$name = Read-Host "Type in the name of the student"$linkedList.AddBefore($currentNode, @{Name=$name;Score=$score})$flag = $false}} }最后我們來運行這兩個方法,對成績單鏈表進行初始化和插入操作,并顯示插入數據后的鏈表:
Write-Host "---Now begin initial---" -ForegroundColor green Initial $linkedList Write-Host "---Now begin insert---" -ForegroundColor green InsertStudent $linkedList Write-Host "---Result---" -ForegroundColor green $linkedList運行結果如下:
我們可以看到,我們不用再去像在C語言中一樣對指針的指向進行操作,取而代之的是一系列已經封裝好了的屬于鏈表對象本身的方法和屬性。比如:
鏈表對象的第一個節點——
$linkedList.First某一結點的下一節點——
$node.Next在鏈表的某一節點前插入一個節點——
$linkedList.AddBefore($currentNode, @{Name=$name;Score=$score})我們可以看到,我們只需要關注節點插入的位置(目標節點)和節點對象本身的數值部分,剩下的對指針部分的操作已經封裝到方法里了。我們只需要選擇指定的方法就可以完成對目標節點前后的插入等操作。PowerShell和C#都是基于.NET的,所以在方法和屬性上基本都是相同的,在這里附上一篇官方的關于鏈表的指南。
總結
以上是生活随笔為你收集整理的链表——PowerShell版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美团的android多渠道包的3种方法
- 下一篇: Editplus快捷键大全