83. 删除排序链表中的重复元素
if(head == null) return null;
ListNode pre = head;
while(pre.next != null) {
if(pre.val == pre.next.val) {
pre.next = pre.next.next;
}else {
pre = pre.next;
}
}
return head;
82. 删除排序链表中的重复元素 II
if(head == null) return head;
ListNode pre = new ListNode(0, head);
ListNode cur = pre;
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 pre.next;
61. 旋转链表
if(head == null) return null;
if(head.next == null) return head;
ListNode l = head;
int len = 1;注意
while(l.next != null) {
len++;
l = l.next;
}
k = k % len;加速
ListNode pre = head;
for(int i = 0; i < k; i++) {将最后一个节点,放到第一位即可
ListNode root = pre;
while(root.next.next != null) {
root = root.next;
}
ListNode end = root.next;
root.next = null;
end.next = pre;
pre = end;
}
return pre;
1796. 字符串中第二大的数字
char[] pre = s.toCharArray();
int max1 = -1, max2 = -1;
for(char c : pre) {
if(Character.isLetter(c)) continue;
int num = c - '0';只有两种情况会影响max1和max2
if(num > max1) {
max2 = max1;
max1 = num;
}
else if(num > max2 && num < max1) {
max2 = num;
}
}
return max2;