zoukankan      html  css  js  c++  java
  • Java 实现一个链表

    public class MyList {
    
        static class Node {// 节点类
            Object data;
            Node next;
    
            public Node(Object data) {// 构造方法,为data赋值
                this.data = data;
                this.next = null;
            }
        }
    
        Node head;
    
        public MyList() {
            head = null;// 链表的构造方法
        }
    
        public void clear() {// 清除链表
            head = null;
        }
    
        public void bianli()// 遍历
        {
            Node p = head;
            while (p != null) {
                System.out.print(p.data + " ");
                p = p.next;
            }
            System.out.println();
        }
    
        public boolean isEmpty()// 推断是否为空
        {
            return head == null;
        }
    
        public int size() {// 节点个数
            Node p = head;
            int sum = 0;
            while (p != null) {
                sum++;
                p = p.next;
            }
            return sum;
        }
    
        // 在指定位置插入元素。下标从0開始
        public void insert(Object d, int pos) {
            if (pos < 0 || pos > size()) {
                throw new RuntimeException("下标错误");
            }
            Node newNode = new Node(d);
            if (pos == 0) {
                newNode.next = head;
                head = newNode;
            } else if (pos >= size() - 1) {
                get(size() - 1).next = newNode;
            } else {
                newNode.next = get(pos);
                get(pos - 1).next = newNode;
            }
        }
    
        public Node get(int pos) {
            if (pos < 0 || pos > size()) {
                throw new RuntimeException("下标错误");
            }
            if (pos == 0)
                return head;
            Node p = head;
            for (int i = 0; i < pos; i++)
                p = p.next;
            return p;
        }
    
        public static void main(String[] args) {
    
            MyList list = new MyList();
            list.insert(10, 0);
            list.insert(20, 1);
            list.insert(30, 0);
            list.insert(40, 1);
    
            System.out.println(list.size());
            list.bianli();
            System.out.println(list.isEmpty());
            System.out.println(list.get(2).data);
            list.clear();
            System.out.println(list.isEmpty());
        }
    
    }
    

    这里写图片描写叙述

  • 相关阅读:
    【CodeForces】835D Palindromic characteristics
    【BZOJ】2006: [NOI2010]超级钢琴
    【比赛】STSRM 09
    【比赛】洛谷夏令营NOIP模拟赛
    【BZOJ】4147: [AMPPZ2014]Euclidean Nim
    【BZOJ】3895: 取石子
    【胡策08】解题报告
    【codevs】3196 黄金宝藏
    【BZOJ】1443: [JSOI2009]游戏Game
    【BZOJ】3105: [cqoi2013]新Nim游戏
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7141019.html
Copyright © 2011-2022 走看看