java 单链表

java 单链表的实现

package Text;
import java.util.*;
public class Link<Item>{
    private Node head=null;
    private Node tail=null;
    private int N=0;
    private class Node{
        Item item;
        Node next;
    }
    /*
    * 在尾部添加数据
    */
    public void addTailData(Item newData){
        Node newNode=new Node();
        newNode.item=newData;
        if(head==null){
            head=newNode;
            tail=newNode;
        }else{
            tail.next=newNode;
            tail=newNode;
        }
        N++;
    }
    /*
    *在头部添加数据
    */
    public void addheadData(Item newData){
        Node newNode=new Node();
        newNode.item=newData;
        if(head==null){
            head=newNode;
            tail=newNode;
        }
        else{
            newNode.next=head;
            head=newNode;
        }
    }
    /*
    *在i点后面插入数据
    */
    public void insertData(int i,Item newData)throws Exception{
        Node newNode=new Node();
        newNode.item=newData;
        int j=0;
        Node p=head;
        if(i<=0){
            throw new Exception("Insert Fail");
        }
        else{
            while(j!=i){
                p=p.next;
                j++;
            }
            newNode.next=p.next;
            p.next=newNode;
            N++;
        }
    }
    /*
    *删除i点的数据
    */
    public void deleteData(int i) throws Exception{
        if(i<0||i>=(N-1)){
            throw new Exception("Delete Fail!");
        }
        else if(i==0){
            head=head.next;
        }
        else{
            Node p=head;
            int j=0;
            while(j!=i-1){
                p=p.next;
                j++;
            }
            p.next=p.next.next;
        }

    }
    /*
    *返回当前链表的节点的个数
    */
    public int size(){
        return N;
    }
    /*
    *打印链表中的元素
    */
    public void print(){
        System.out.print("head-->tail:  ");
        while(head!=null){
            System.out.printf("%s-->",head.item);
            //System.out.print(head.item);
            //System.out.print("-->");
            head=head.next;
        }
        System.out.print("null");
    }
    public static void main(String[] args) throws Exception{
        Link<String> link=new Link<String>();
        link.addTailData("aa");
        link.addheadData("bb");
        link.addTailData("cc");
        link.addheadData("jj");
        link.addTailData("ee");
        link.deleteData(3);
        link.print();
    }
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值