技能树-基础之章-数据结构-链表操作

单链表

遍历

public static void forLinked(Linked linked){
    Linked temp = linked;
    while(temp != null){
        temp = temp.nextNode;
    }
}

增加

public static void addLinked(Linked linked,int data) {
    Linked newNode = new Linked(data);
    Linked temp = linked;
    while(temp.nextNode!=null){
        temp =temp.nextNode;
    }
    temp.nextNode = newNode;
}

插入

public static void insertLinked(Linked linked,int value,int index){
    Linked newNode = new Linked(value);
    Linked temp = linked;
    while(temp !=null){
        index--;
        if(index == 1){
            newNode.nextNode = temp.nextNode;
            temp.nextNode = newNode;
        }else{
            temp = temp.nextNode;
        }
    }

}

删除

public static void deleteLinked(Linked linked,int index){
    Linked temp = linked;
    while(temp !=null){
        index--;
        if(index == 1){
            temp.nextNode = temp.nextNode.nextNode;
        }else{
            temp = temp.nextNode;
        }
    }
}

重点在于使用指针指向头结点,遍历指针

你可能感兴趣的:(java)