链表——PowerShell版
鏈表是由一系列節(jié)點(diǎn)串連起來組成的,每一個(gè)節(jié)點(diǎn)包括數(shù)值部分和指針部分,上一節(jié)點(diǎn)的指針部分指向下一節(jié)點(diǎn)的數(shù)值部分所在的位置。
在C語言中我們有兩種方式來定義鏈表——
1、定義結(jié)構(gòu)體:來表示鏈表中的節(jié)點(diǎn),節(jié)點(diǎn)中包含數(shù)值部分和指針部分。將一個(gè)節(jié)點(diǎn)的指針部分指向另一個(gè)節(jié)點(diǎn)的數(shù)值部分,這兩個(gè)結(jié)構(gòu)體之間就形成了一個(gè)鏈表。
2、不定義結(jié)構(gòu)體:用一個(gè)數(shù)組來表示鏈表的數(shù)值部分,用另外一個(gè)數(shù)組來表示每個(gè)數(shù)值所對應(yīng)的指針部分。
在PowerShell中定義一個(gè)鏈表更加簡潔:
$linkedList = New-Object System.Collections.Generic.LinkedList[HashTable]其中HashTable相當(dāng)于我們在C語言中定義的結(jié)構(gòu)體中的數(shù)值部分,而對于鏈表中數(shù)值進(jìn)行的操作都被封裝成了一系列鏈表對象的方法。
現(xiàn)在我們舉一個(gè)現(xiàn)實(shí)生活中的例子——
考試結(jié)束,老師排好了一個(gè)成績單(按成績從高到低),現(xiàn)在來了個(gè)插班生,我們要把這個(gè)插班生的考試成績插入到本班的成績單中。
首先我們寫一個(gè)方法,將排好的成績單錄入到一個(gè)鏈表中:
#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}) } }然后我們寫一個(gè)方法,將插班生的成績插入到已排好序的成績單鏈表中:
#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}} }最后我們來運(yùn)行這兩個(gè)方法,對成績單鏈表進(jìn)行初始化和插入操作,并顯示插入數(shù)據(jù)后的鏈表:
Write-Host "---Now begin initial---" -ForegroundColor green Initial $linkedList Write-Host "---Now begin insert---" -ForegroundColor green InsertStudent $linkedList Write-Host "---Result---" -ForegroundColor green $linkedList運(yùn)行結(jié)果如下:
我們可以看到,我們不用再去像在C語言中一樣對指針的指向進(jìn)行操作,取而代之的是一系列已經(jīng)封裝好了的屬于鏈表對象本身的方法和屬性。比如:
鏈表對象的第一個(gè)節(jié)點(diǎn)——
$linkedList.First某一結(jié)點(diǎn)的下一節(jié)點(diǎn)——
$node.Next在鏈表的某一節(jié)點(diǎn)前插入一個(gè)節(jié)點(diǎn)——
$linkedList.AddBefore($currentNode, @{Name=$name;Score=$score})我們可以看到,我們只需要關(guān)注節(jié)點(diǎn)插入的位置(目標(biāo)節(jié)點(diǎn))和節(jié)點(diǎn)對象本身的數(shù)值部分,剩下的對指針部分的操作已經(jīng)封裝到方法里了。我們只需要選擇指定的方法就可以完成對目標(biāo)節(jié)點(diǎn)前后的插入等操作。PowerShell和C#都是基于.NET的,所以在方法和屬性上基本都是相同的,在這里附上一篇官方的關(guān)于鏈表的指南。
總結(jié)
以上是生活随笔為你收集整理的链表——PowerShell版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美团的android多渠道包的3种方法
- 下一篇: Editplus快捷键大全