劍指Offer(書):反轉鏈表
阿新 • • 發佈:2018-08-08
col after 分析 listnode head tno eve offer 開始
題目:輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
分析:要分清他的前一個節點和後一個節點,開始的時候前節點為null,後節點為head.next,之後,反轉。
public ListNode ReverseList(ListNode head) { if (head == null) { return null; } if(head.next==null){ return head; } ListNode preNode = null; ListNode currentNode= head; ListNode afterNode = head.next; while (currentNode!=null){ currentNode.next=preNode; preNode = currentNode; if (afterNode.next == null) { afterNode.next=currentNode; break; } currentNode=afterNode; afterNode = afterNode.next; } return afterNode; }
劍指Offer(書):反轉鏈表