首页 > 其他分享 >代码随想录刷题day 3 | 链表理论基础 203.移除链表元素 707.设计链表 206.反转链表

代码随想录刷题day 3 | 链表理论基础 203.移除链表元素 707.设计链表 206.反转链表

时间:2024-07-05 21:43:15浏览次数:17  
标签:head ListNode val int 随想录 next 链表 移除

203. 移除链表元素

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode virHead = new ListNode(0, head);
        ListNode tmp = virHead;
        while(tmp.next != null){
            if(tmp.next.val == val){ 
                tmp.next = tmp.next.next;
            }else{ 
                tmp = tmp.next;
            }
        }
        return virHead.next;
    }
}

707. 设计链表

class ListNode{
    int val;
    ListNode next;
    public ListNode(){
    }
    public ListNode(int val){
        this.val = val;
    }
    public ListNode(int val, ListNode next){
        this.val = val;
        this.next = next;
    }
}

class MyLinkedList {
    int length;
    ListNode head;
    public MyLinkedList() {
        this.head = new ListNode();
    }
    public int get(int index) {
        if(index < 0 || index >= this.length) return -1;
        ListNode tmp = head;
        for(int i = 0; i <= index; i++){
            tmp = tmp.next;
        }
        return tmp.val;
    }
    public void addAtHead(int val) {
        this.addAtIndex(0, val);
    }
    public void addAtTail(int val) {
        this.addAtIndex(this.length, val);
    }
    public void addAtIndex(int index, int val) {
        if(index > this.length || index < 0) return;
        ListNode cur = this.head;
        for(int i = 0; i < index; i++){
            cur = cur.next;
        }
        ListNode tmp = new ListNode(val, cur.next);
        cur.next = tmp;
        this.length += 1;

    }
    public void deleteAtIndex(int index) {
        if(index >= this.length || index < 0) return;
        ListNode pre = this.head;
        for(int i = 0; i < index; i++){
            pre = pre.next;
        }
        pre.next = pre.next.next;
        this.length -= 1;
    }
}

206. 反转链表

class Solution { //迭代
    public ListNode reverseList(ListNode head) {
        ListNode pre = head;
        if(head == null) return head;
        ListNode next = head.next;
        pre.next = null;
        while(next != null){
            ListNode nextIter = next.next;
            next.next = pre;
            pre = next;
            next = nextIter;
        }
        return pre;
    }
}

class Solution { //递归
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

每天都做点,慢慢也就进步了。不过还是有点畏难情绪,做着做着就偷懒了,慢慢改善吧。

标签:head,ListNode,val,int,随想录,next,链表,移除
From: https://www.cnblogs.com/12sleep/p/18286640

相关文章