題解 | #反轉(zhuǎn)鏈表01 優(yōu)化#
反轉(zhuǎn)鏈表
http://www.fangfengwang8.cn/practice/75e878df47f24fdc9dc3e400ec6058ca
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { //新鏈表 ListNode newHead = null; while (head != null) { //先保存訪問的節(jié)點的下一個節(jié)點,保存起來 //留著下一步訪問的 ListNode temp = head.next; //每次訪問的原鏈表節(jié)點都會成為新鏈表的頭結(jié)點, //其實就是把新鏈表掛到訪問的原鏈表節(jié)點的 //后面就行了 head.next = newHead; //更新新鏈表 newHead = head; //重新賦值,繼續(xù)訪問 head = temp; } //返回新鏈表 return newHead; } }
與01不同點在于鏈表的掛接和更新 去掉一個next的事
但明顯好理解了很多!