《LeetCode力扣练习》代码随想录——链表(设计链表---Java)

《LeetCode力扣练习》代码随想录——链表(设计链表—Java)



刷题思路来源于 代码随想录

707. 设计链表
  • 虚拟头结点
    class MyLinkedList {
    
        class ListNode{
    
            int val;
            ListNode next;
    
            ListNode(){
    
            }
    
            ListNode(int val){
                this.val=val;
            }
    
            ListNode(int val,ListNode next){
                this.val=val;
                this.next=next;
            }
    
        }
    
        private int size;
        private ListNode dummyHead;
    
        public MyLinkedList() {
    
            this.size=0;
            this.dummyHead=new ListNode(0,null);
    
        }
        
        public int get(int index) {
    
            if(this.size==0||index>=this.size){
                return -1;
            }
    
            ListNode current=this.dummyHead.next;
    
            while(index>0){
                current=current.next;
                index--;
            }
    
            return current.val;
    
        }
        
        public void addAtHead(int val) {
    
            addAtIndex(0,val);
            return;
    
        }
        
        public void addAtTail(int val) {
    
            addAtIndex(this.size,val);
            return;
    
        }
        
        public void addAtIndex(int index, int val) {
    
            if(index>this.size){
                return;
            }
    
            ListNode current=this.dummyHead;
    
            while(index>0){
                current=current.next;
                index--;
            }
    
            ListNode newNode=new ListNode(val,current.next);
            current.next=newNode;
            this.size++;
    
            return;
    
        }
        
        public void deleteAtIndex(int index) {
    
            if(this.size==0||index>=this.size){
                return;
            }
    
            ListNode current=this.dummyHead;
    
            while(index>0){
                current=current.next;
                index--;
            }
    
            current.next=current.next.next;
            this.size--;
    
            return;
    
        }
    }
    
    /**
     * Your MyLinkedList object will be instantiated and called as such:
     * MyLinkedList obj = new MyLinkedList();
     * int param_1 = obj.get(index);
     * obj.addAtHead(val);
     * obj.addAtTail(val);
     * obj.addAtIndex(index,val);
     * obj.deleteAtIndex(index);
     */
    

你可能感兴趣的:(LeetCode,leetcode,链表,java)