Java实现单链表常见操作

class Node{
    private int data;
    private Node next;
    private static Node head=null;
    public Node(int data){
        this.data=data;
    }
    //增加结点
    public static void addNode(int d){
        Node node=new Node(d);
        if(head==null){
            head=node;
            return;
        }
        Node temp=head;
        while(temp.next!=null)
            temp=temp.next;
        temp.next=node;
    }
    public static int size(){
        Node temp=head;
        int n=0;
        while(temp!=null){
            n++;
            temp=temp.next;
        }
        return n;
    }
    //在pos位置上插入结点
    public static void insertNode(int d,int pos){
        if(pos<1||pos>head.size())
            throw new IndexOutOfBoundsException();//抛出角标异常
        Node node=new Node(d);
        int k=1;
        Node temp=head;
        while(temp!=null&&k<pos){//找到需要插入的位置
            temp=temp.next;
            k++;
        }
        Node q=temp.next;
        node.next=q;
        temp.next=node;
    }
    //删除结点
    public static void delete(int pos){
        Node temp=head;
        if(temp==null||pos<1||pos>head.size())
            throw new IndexOutOfBoundsException();//抛出角标异常
        while(temp!=null&&pos>1){
            temp=temp.next;
            pos--;
        }
        temp.next=temp.next.next;
    }
    //遍历结点
    public static void print(){
        Node temp=head;
        while(temp!=null) {
            System.out.println(temp.data);
            temp=temp.next;
        }
    }
}
public class exercise4 {
    public static void main(String[] args) {
        Node head=null;
        head.addNode(3);
        head.addNode(4);
        head.addNode(5);
        head.addNode(6);
        head.insertNode(8,1);
        head.delete(2);
        head.print();
    }
}

猜你喜欢

转载自blog.csdn.net/sir_ti/article/details/80364650