代码随想录训练营第三天 |203.移除链表元素, 707.设计链表, 206.反转链表

第三天是链表,要注意的是可以创建虚拟头节点来进行链表操作。

203. 移除链表元素

复制代码
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode temp = new ListNode(-1);
        temp.next = head;
        ListNode cur = temp;

        while(cur.next!=null){
            if(cur.next.val == val){
                cur.next = cur.next.next;
            }
            else{
                cur = cur.next;
            }
        }
        return temp.next;
    }
}
复制代码

链表中基础的删除节点,创建一个虚拟节点,虚拟节点的next 为head, 然后不断next,如果这个虚拟节点的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 {
    private int size;
    private ListNode head;
    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }
    
    public int get(int index) {
        if(index < 0 || index >= size){
            return -1;
        }
        ListNode temp = head;
        for(int i = 0;i<= index; i++){
            temp = temp.next;
        }
        return temp.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 < 0 || index > size){
            return; 
        }
        size ++;
        ListNode temp = head;
        for(int i = 0; i<index; i++){
            temp = temp.next;
        }
        ListNode cur = new ListNode(val);
        cur.next = temp.next;
        temp.next = cur;
    }
    
    public void deleteAtIndex(int index) {
        if(index < 0 || index>= size){
            return;
        }
        size--;
        ListNode temp = head;
        for(int i = 0;i < index; i++){
            temp = temp.next;
        }
        temp.next = temp.next.next;
    }
}

复制代码

需要先创建一个ListNode class,然后再根据题意,实现链表的查和增删功能

 

206. 反转链表

复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        ListNode post = null;

        while(cur != null){
            post = cur.next;
            cur.next = pre;
            pre = cur;
            cur = post;
        }
        return pre;
    }
}
复制代码

使用两个节点来记录cur节点的前节点和后节点,然后让cur.next指向前节点

 

第三天结束了,目前来说第三天就开始有中等题了,对刚入门的同学可能需要花更多的时间理解

 

posted @   小猫Soda  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示