关于java:单链表的增删改查

35次阅读

共计 1518 个字符,预计需要花费 4 分钟才能阅读完成。

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

    ListNode head;// 头结点
    ListNode tail;// 尾结点
    
    int size;
    
    public MyLinkedList(){
        head = null;
        tail = null;
        size = 0;
    }
    
    // 插入方法 
    
    public void insert(int position, int number){if(position > size){return;}
        
        ListNode newNode = new ListNode(number);
        // 要插入的地位是 0(即为头部)// case 1 : 头部插入
        if(position == 0){
            newNode.next = head;
            head = newNode;
            // 判断尾结点是不是 null,如果是 null 阐明这是插入的第一个元素
            if(tail == null){tail = newNode;}
            size++;
        } 
        
        // case 2 : 尾部插入
        else if(position == size){this.append(number);
        } 
        // case 3 : 两头插入
        else {
            
            // 找到插入地位之前的节点
            ListNode prev = head;
            for (int i = 0; i < position - 1; i++) {prev = prev.next;}
            
            ListNode next = prev.next;
            newNode.next = next;
            prev.next = newNode;
            
            size++;
            
        }
    }

    
    public void append(int number){ListNode newNode = new ListNode(number);
        
        if(tail == null){tail = newNode;} else {
            tail.next = newNode;
            tail = newNode;
        }
        
        size++;
        
    }
    
    // 删除
    public void delete(int number){
        
        // 删除头结点
        if(head != null && head.val == number){
            head = head.next;
            size--;
            // 如果 size==0  阐明只有一个元素
            if(size == 0) {tail = head;}
        }
        else 
        {
            ListNode prev = head;     
            ListNode current = head;  
            
            while(prev != null && current != null){if(current.val == number){if(current == tail){tail = prev;}
                    
                    prev.next = current.next;
                    size--;
                    return;
                }
                prev = current;
                current = current.next;
            }
        }
    }
    
    // 查找   返回地位
    public int search(int number){
        
        ListNode current = head;
        for (int i = 0; current != null; i++) {if(current.val == number){return i;}
            current = current.next;
        }
        
        return -1;
    }
    
    // 批改
    public int update(int oldValue, int newValue){
        
        ListNode current = head;
        for (int i = 0; current != null; i++) {if(current.val == oldValue){
                current.val = newValue;
                return i;
            }
            current = current.next;
        }
        
        return -1;
    }
    
    public static void main(String[] args) {}}

正文完
 0