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.next
to for remove / delete, the curr = curr.next
should 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