栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java数据结构之链表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java数据结构之链表

public class linklist {
    private class Node{
        private T info;
        private Node next;
        public Node(T info,Node next){
            this.info = info;
            this.next = next;
        }
    }
    private Node head;//头节点
    private int size;//链表长度
    //构造方法
    public linklist(Node head,int size){
        this.head = head;
        this.size = size;
    }
    public linklist() {
    }

    
    public int getSize(){
        return this.size;
    }
    //向链表头节点前面添加一个节点,其数据域为info
    public void addHead(T info){
        this.head = new Node(info,head);
        this.size++;
    }
    //尾插法
    public void addLast(T info){
        this.add(info,this.size);
    }
    //插入指定位置
    public void add(T info,int index){
        if(index < 0 || index > size) return;
        else if(index == 0){
            addHead(info);
            return;
        }
        Node pre = this.head;//找到添加位置的前一个节点
        for(int i = 0;i < index-1;i++){
            pre = pre.next;
        }
        Node node = new Node(info,pre.next);
        pre.next = node;
        this.size++;
    }
    //删除任意位置的结点
    public void delete(Node head,int index){
        if(head == null) return;
        if(index < 0 || index > size-1) return;
        if(index == 0){
            this.head = head.next;
        }
        Node front = this.head;//指向删除节点前面的节点
        Node rear = this.head;//指向删除节点
        for(int i = 0;i");
            }
            else{
                System.out.print(h.info);
            }
            h = h.next;
        }
        System.out.println('n');
    }
    public static void main(String[] args) {
        linklist s = new linklist<>();
        for (int i = 0; i < 5; i++) {
            s.addHead(i);
        }
        s.add(7,4);
        System.out.println(s.search(3));
        s.travel(s.head);
        s.delete(s.head,4);
        s.travel(s.head);
        s.invert(s.head);
        s.travel(s.head);
    }
}

输出结果:

1
4->3->2->1->7->0

4->3->2->1->0

0->1->2->3->4
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666153.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号