链表(头插、尾插、删除)

//Node构造方法

public class Node<T> {
    Node<T> next;
    T value;

    public Node(Node<T> next,T value){
        this.next = next;
        this.value = value;

    }
}
/**
 * 链表:头插、尾插,删除
 * @param <T> 类型
 */
public class Link<T> {
    private Node<T> head = null;
    private Node<T> tail = null;

    public void add(T value){    //头插

       Node<T> n = new Node<T>(null,value);   //创建一个结点,next为空
       if(head == null){   //如果没有数据,则头节点、尾节点 = 这个节点;
           head = tail = n;
       }else{
           n.next = head;  //有数据,先把n的next给head,head再指向n
           head = n;
       }


    }
    public void append(T value) {  //尾插
        Node<T> n = new Node<T>(null, value);  //创建一个新节点n
        if (tail != null) {  //有数据,
            tail.next = n;   //则最后一个的next = n
            tail = n;   // tail指向n
        } else {
            head = tail = n;   //无数据,head = tail = n
        }


    }


    public void delete(int index){

        Node<T> temp = head;
        if(index == 0){  //删除第一个,head直接后移一位
            head = head.next;
            return;
        }
        for(int i = 0;i < index - 1;i++,temp = temp.next){  //把temp定位到删除元素的前一个元素
            if(temp.next == null){  //越界异常
                throw new IndexOutOfBoundsException();
            }
        }


        if(temp.next == tail){  //如果删除的元素为最后一个,则移动tail到删除元素前一个元素即为temp
            tail = temp;
        }
        temp.next =temp.next.next; //删除的为中间元素,则temp= temp.next.next
    }
    @Override
    public String toString(){  //链表元素放入s,再输出
        StringBuilder s = new StringBuilder();
        if(head != null){

            for(Node<T> temp = head; temp != null;temp = temp.next){
                if(s.length() > 0){
                    s.append(",");
                }
               s.append(temp.value);

            }
        }

        return s.toString();
    }
//main方法
    public static void main(String[] args){
        Link<Integer> link = new Link<>();

        link.add(50);
        link.append(20);
        link.append(30);
        link.append(40);

        link.delete(2);
       System.out.println(link);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值