234 LinkedList234PalindromeLinkedList
Question: Why my code return false when comparing negative numbers like followings [-16557,-8725,-29125,28873,-21702,15483,-28441,-17845,-4317,-10914,-10914,-4317,-17845,-28441,15483,-21702,28873,-29125,-8725,-16557]
Answer: I use the ArrayList, Interger as on object, can only compare numbers between 2^7 to -2^7+1. So, for the object, we should use equals().
Further Question: ? How do we write equals() for Compare method?
203 RemoveLinkedListElements
1. Forgot move thecurr‘point’ to the next
when other if statement added
2. Usage of !=Null
We can use .next and .next.next to delete elements, but that means the current and next should be not null. ——> If we use .next.nextto for remove / delete, the curr = curr.nextshould be in the else statement
19 RemoveNthNodeFromEndOfList
自己第一反應做法是reverse list
1. Forgot the specialty of removing head element
2. if reverse you have to reverse back
看了一個solution的第一句話就曉得了通用辦法,存在V2
1. 對于刪除頭結點的判斷,嵌套的if else太過冗余,想想別的方法 4/15/2016
后來發現想多了。head = head.next 包含了head = null這種情況
//Create the two pointers ListNode faster = head; ListNode slower = head; for (int i = 0; i < n; i++) { faster = faster.next; }//Find the to-be-delete element (slower) if (faster == null) {//delete the head head = head.next; } else {//not delete head while (faster.next != null) { faster = faster.next; slower = slower.next; } slower.next = slower.next.next; }第一部分的for可以與第二部分while合并 - by網友先隔開n個再同時移動兩個指針 ===> 一個循環中先數n個移動faster指針再一起移動兩個指針
刪除頭結點的特殊性,其實可以在head前面再加個節點來解決!
LinkedList by Categories
總是忘了移動pointer
e.g.237 234 203 19PRint
忘記移動index這個point
關于reverse list究竟需要幾個pointer
畫一個圖,模擬走兩步,基本可以確定需要幾個pointer。主要是頭結點的特殊性,所以第一步的head算是特例。一般情況head不會作為pointer亂移動,所以寧可多設個pointer,不亂。忘記了刪除頭結點的特殊性
e.g. 19
比如LL19removeNthFromEnd, 在反向list里面有可能刪除的是頭結點.在沒有用反向做的時候,當n == listlength 的時候也是刪除頭結點啊!判斷 != null 的特殊性
同時判斷.next != null和curr != null需要if else