java数据结构--单向链表

 

一.类型和节点定义

用内部类的方式来定义链表的属性

public class SingleLinkList {
    //头节点为空
    private Node head = null;

  private static class  Node{
        private int data;
        private Node next;

       public Node(int data, Node next) {
           this.data = data;
           this.next = next;
       }
}

注意:这里的索引都是从1开始的,不是从0

二.头插法插入新节点

 public void addFirst(int data){

        Node p = head;

        head = new Node(data,null);

        head.next = p;
    }

三.尾插法插入新节点

  public void addLast(int data){
        //先找到最后一个节点
        Node p  = head;
        if(p == null){
            addFirst(data);
            return;
        }
        while ( p.next != null ){
            p = p.next;
        }
        p.next = new Node(data,null);
    }

四.遍历链表

 public void printList(){
        Node p = head;
        while (p != null){
            System.out.println(p.data);
            p = p.next;
        }
    }

五.根据索引查找指定节点

 public  Node findIndex(int index){
        Node p = head;
        int i = 1;
        while(p != null){

            if(i == index){
                return  p;
            }
            i++;
            p = p.next;
        }
        return null;
    }

六.头部删除节点

   public void removeFirst(){
        if(head == null){
            throw new IllegalArgumentException("头结点为空");
        }
        head = head.next;
    }

七.根据索引删除指定位置的节点

 public void remove(int index){
        if(index == 1){
            removeFirst();
            return;
        }

        Node prev = findIndex(index - 1);
        if(prev == null){
            throw new IllegalArgumentException(String.format("参数不合法:%d",index));
        }

        Node removed = prev.next;
        if(removed == null){
            throw new IllegalArgumentException(String.format("参数不合法:%d",index));
        }
        prev.next = removed.next;


    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值