系列博客目录
文章目录
1. for循环更新部分
不能下面代码的第二行,只能是第一行。
j += label==0 ? ((numRows-i-1)*2) : i*2)
j = j + label==0 ? ((numRows-i-1)*2) : i*2)
j = j + label==0 ? ((numRows-i-1)*2) : i*2
这里的问题在于,条件表达式 label == 0 ? ((numRows-i-1)*2) : i*2
的优先级低于 +
运算符。表达式会先计算 j + label
再比较是否== 0
,它的结果是一个布尔值(True
或 False
),然后 ?
运算符(条件运算符)会根据该布尔值选择两部分中的一部分(((numRows-i-1)*2)
或 i*2
),接着赋值给j
。
2.没有头结点可以自己创建一个头结点来简化问题。
19.删除链表的倒数第 N 个结点
链接
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode root = new ListNode();
root.next = head;
int count = n+1;
head = root;
ListNode res = head;
while(head!=null){
if(count>0){
count--;
}else {
res = res.next;
}
head = head.next;
}
res.next = res.next.next;
return root.next;
}
}
3.链表中while循环判定条件可以是head!=null或者head.next!=null,要根据情况判定。
4.数组中我们经常用当前节点和前面节点作比较,链表中用当前节点的后面结点进行比较,这样方便删除节点。
82题。
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode dummyNode = new ListNode(0,head);
ListNode cur = dummyNode;
while(cur.next!= null && cur.next.next != null){
if(cur.next.val == cur.next.next.val){
int x = cur.next.val;
while(cur.next!=null && cur.next.val==x ){
cur.next = cur.next.next;
}
}else {
cur = cur.next;
}
}
return dummyNode.next;
}
}