數(shù)據(jù)結(jié)構(gòu) - java翻轉(zhuǎn)鏈表是如何實現(xiàn)的?
問題描述
public class Node { public int value; public Node next; public Node(int data) {this.value = data; } public Node reverse(Node head) {Node pre = null;Node next = null;while (head != null) { next = head.next; head.next = pre; pre = head; head = next;}return pre; }
這段代碼while循環(huán)中他是如何翻轉(zhuǎn)的?想要詳細(xì)一點的,debug了幾次還是沒弄懂具體是怎么回事
問題解答
回答1:參考一下,理解目的就比較好理解了。容易混亂的地方就是從右往左來處理,因為得先把后面的東西存起來,不然被覆蓋掉就丟了。
prehead +----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead nextnext = head.next;+----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead next+----+ <+ +----+ +----+| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| | head.next = pre;+----+ next preheadpre = head;+----+ <+ +----+ +----+ head = next;| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| |+----+回答2:
Ps:建議先多了解一下鏈表
相關(guān)文章:
1. mysql - 一個表和多個表是多對多的關(guān)系,該怎么設(shè)計2. python 如何實現(xiàn)PHP替換圖片 鏈接3. html5 - iOS的webview加載出來的H5網(wǎng)頁,怎么修改html標(biāo)簽select的樣式字體?4. 一個mysql聯(lián)表查詢的問題5. python如何不改動文件的情況下修改文件的 修改日期6. javascript - git clone 下來的項目 想在本地運行 npm run install 報錯7. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應(yīng)用上有什么區(qū)別?8. angular.js - 三大框架react、vue、angular的分析9. python - django 里自定義的 login 方法,如何使用 login_required()10. 主從備份 - 跪求mysql 高可用主從方案
