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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值