數據結構 - java翻轉鏈表是如何實現的?
問題描述
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循環中他是如何翻轉的?想要詳細一點的,debug了幾次還是沒弄懂具體是怎么回事
問題解答
回答1:參考一下,理解目的就比較好理解了。容易混亂的地方就是從右往左來處理,因為得先把后面的東西存起來,不然被覆蓋掉就丟了。
prehead +----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead nextnext = head.next;+----+ +----+ +> +----+| | | | | | || | | | | | || | | | | | |+----+ +----+ | +----+| | | | | | || | | | | | |+----+ +-+--+ | +----+ | | +-----+ prehead next+----+ <+ +----+ +----+| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| | head.next = pre;+----+ next preheadpre = head;+----+ <+ +----+ +----+ head = next;| | | | | | || | | | | | || | | | | | |+----+ | +----+ +----+| | | | | | || | | | | | |+----+ | +-+--+ +----+| |+----+回答2:
Ps:建議先多了解一下鏈表
相關文章:
1. javascript - 怎么下載vue csp版本的2.0或者以上?2. golang - 用IDE看docker源碼時的小問題3. javascript - 求救!網頁播放視頻只有聲音沒有畫面,網頁上傳視頻文件時怎么知道視頻的編碼為H264還是MPEG4??4. javascript - webpack --hot 熱重載無效的問題5. io - java 文件操作,如何向指定的位置插入內容 (不是替換內容) ?6. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?7. javascript - vue使用videojs+videojs-contrib-hls報錯8. dockerfile - [docker build image失敗- npm install]9. mysql如何配置遠程php外網鏈接數據庫10. Python 爬蟲 遇到的問題(手淘問大家)
