leetcode-03-[203]移除链表元素[707]设计链表[206]反转链表

本节重点:虚拟头节点

小重点:设计链表,比较新颖的题型

一、[203]移除链表元素

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

二、[707]设计链表

重点:定义size!!!,并在添加时,删除时改变size大小

class MyLinkedList {
    int size;
    ListNode dummyHead;
    public MyLinkedList() {
        size=0;
        dummyHead=new ListNode(-1);
    }
    
    public int get(int index) {
        if(index<0||index>=size){
            return -1;
        }
        ListNode cur=dummyHead;
        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<0){
            index=0;
        }
        if(index>size)
        {
            return;
        }
        ListNode pre=dummyHead;
        for(int i=0;i<index;i++)
        {
            pre=pre.next;
        }
        ListNode toAdd=new ListNode(val);
        toAdd.next=pre.next;
        pre.next=toAdd;
        size++;
    }
    
    public void deleteAtIndex(int index) {
        if(index<0||index>=size) {
            return;
        }
        //注意
        size--;
        ListNode pre=dummyHead;
        for(int i=0;i<index;i++)
        {
            pre=pre.next;
        }
        pre.next=pre.next.next;
    }
}

三、[206]反转链表

重点:理解逻辑,找对方法!!!

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre=null;
        ListNode cur=head;
        while(cur!=null)
        {
            ListNode tmp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tmp;
        }
        return pre;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值