单向链表

2019-12-25  本文已影响0人  zzz_0427

链表是以节点的方式存储数据,每个节点包含data域和指向下个节点地址的next域。

相邻的节点内存地址不一定是相邻的。

最后的节点的next域为null。

代码

public class SingleLinkList{

    public static void main(String[] args){

        SingleLinkList linkList =new SingleLinkList();

        linkList.add(0,10);//在index =0 添加10

        linkList.getSize();

        linkList.add(1,20);//在index = 1添加20

        linkList.getSize();

        linkList.add(1,30);//在index = 0,1  之间添加30

        linkList.getSize();

        for (int i =0; i< linkList.count;i++){

            System.out.printf("%d\t",linkList.getValue(i));

        }

    }

    //头节点

    private Node head;

    private int count;

    //构造函数

    public SingleLinkList() {

        this.head =new Node<>(null,null);

        count =0;

    }

    public int getSize(){

        System.out.println("链表长度为:" +count);

        return count;

    }

    /**

        * 获取节点

        * @param index

         * @return

     */

    public Node getNode(int index){

        if (index <0 || index >count){

            throw new IndexOutOfBoundsException();

        }

        Node node =head;

        for (int i=0 ;i <= index;i++){

            node = node.next;

        }

        return node;

    }

    /**

    * 获取节点的值

    */

    public E getValue(int index){

        return getNode(index).getData();

    }

    /**

    * 添加节点

    * @param index

    * @param data

    */

    public void add(int index,E data){

        if (index >count){

            throw new RuntimeException("链表长度为"+count +",索引长度"+index+"不能大于链表长度!");

        }

        Node node =new Node(data,null);

        if (index ==0){

            head.next = node;

            count++;

        }else{

            Node lastIndexNode = getNode(index-1);

            Node indexNode  = getNode(index);

            lastIndexNode.next = node;

            node.next = indexNode;

        if (indexNode !=null) {//indexNode不为null  则在2个节点之间插入

                node.next = indexNode;

         }//indexNode为null  则在链表rear插入*/

          count++;

        }

}

class Node{

    private E data;

    private Nodenext;

    public Node(E data, Node next) {

    this.data = data;

    this.next = next;

}

public E getData() {

    return data;

}

public void setData(E data) {

    this.data = data;

}

public Node getNext() {

    return next;

}

public void setNext(Node next) {

    this.next = next;

}

}

上一篇 下一篇

猜你喜欢

热点阅读