剛學java,最近老師布置了一個題目,要求洗掉帶頭結點單鏈表的最小元素,在糾結洗掉所有的最小元素應該如何實作,一點思路也沒有,有沒有大佬指點一下
uj5u.com熱心網友回復:
先遍歷一遍找出最小值,再遍歷一遍發現與最小元素相等的節點洗掉之uj5u.com熱心網友回復:
在遍歷的之前定義一個變數min=Integer. max,每當遍歷一個節點時如果該節點的值小于min則保存該節點,遍歷結束后將保存的節點的值改為它的下一個節點的值然后洗掉下一個節點uj5u.com熱心網友回復:
搞懂了uj5u.com熱心網友回復:
遍歷一次就可以了,代碼如下:Node currentNode = 鏈表.head;
Node minNodefront = null;
Node minNode = 鏈表.head;
while(currentNode.next != null){
if( minNode.data > currentNode.next.data ){
minNode = currentNode.next;
minNodeFront = currentNode;
}
node = node.next;
}
if( minNodefront == null ){
鏈表.head = minNode;
} else {
minNodeFront.next = minNode.next;
}
管理員還說我灌水,刪了我評論,不能忍
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/108887.html
標籤:Eclipse
