day3 代码随想录刷题笔记---链表理论基础。

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) {
        ListNode prehead=new ListNode();
        prehead.next=head;
        ListNode node=head,pre=prehead;
        while(node!=null){
            if(node.val==val){
                ListNode next=node.next;
                pre.next=next;
                node=next;
            }else{
                pre=pre.next;
                node=node.next;
            }
        }

        return prehead.next;

    }
}

707.设计链表

链表总是我的老大难,总是对应不上指针的位置和数字

class MyLinkedList {
    int size;
    ListNode head;

    public MyLinkedList() {
        size=0;
        head=new ListNode(0);

    }
    
    public int get(int index) {
        if(index>=size ||index<0 ) return -1;
        ListNode node=head;
        for(int i=0;i<=index;++i){
            node=node.next;
        }
        return node.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 ;
       if(index<=0) index=0;
       ListNode node=head;
       for(int i=0;i=size) return ;
        ListNode node=head;
        for(int i=0;i

206 反转链表

熟能生巧的题

/**
 * 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 reverseList(ListNode head) {
        if(head==null) return head;
        ListNode pre=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode node=cur;
            cur=cur.next;
            node.next=pre;
            pre=node;
        }
        return pre;

    }
}

你可能感兴趣的:(leetcode刷题,链表,算法,leetcode)