移除链表元素(力扣203)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null&& head.val == val){//排除所有头节点为val
head = head.next;
}
if(head == null) return head;
ListNode cur = head;
ListNode pre = head.next;
while(pre != null){
if(pre.val == val){
cur.next = pre.next;
}else{
cur = pre;
}
pre = pre.next;
}
return head;
}
}
设计链表(力扣707)
写的实在是折磨时不时就Cannot read field “next” because“ ” is null
写的时候还是多注意边界条件,多关注一下size链表长度的变化;
class MyLinkedList {
int size;//链表长度
LinkList hade;//虚拟头节点
public MyLinkedList() {
hade = new LinkList(0);
size = 0;
}
public int get(int index) {
if(index<0 || index > size-1){
return -1;
}
LinkList cur = hade;
//包含一个虚拟头节点,所以查找第 index+1 个节点
for(int i = 0; i <= index; i++){
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if(index > size){
return;
}
index = Math.max(0,index);
size++;
LinkList cur = hade;
//此时cur指针在下标index-1的位置
for(int i = 0; i < index; i++){
cur = cur.next;
}
LinkList newhade = new LinkList(val, cur.next);
cur.next = newhade;
}
public void deleteAtIndex(int index) {
if(index >= size|| index < 0){
return;
}
size--;
LinkList cur = hade;
for(int i = 0; i < index; i++){
cur = cur.next;
}
cur.next = cur.next.next;
}
}
class LinkList{
int val;
LinkList next;
LinkList(int val){
this.val = val;
}
LinkList(int val, LinkList next){
this.val = val;
this.next = next;
}
}
反转链表(力扣206)
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = null;
ListNode pre = head;
//双指针法
while(pre != null){
ListNode tmp = pre.next;
pre.next = cur;
cur = pre;
pre = tmp;
}
return cur;
}
}
每日一题(2413)
class Solution {
public int smallestEvenMultiple(int n) {
return n % 2 == 0 ? n : n*2;
}
}