Java实现单向链表

/**
 * Created by ****** on 2017/8/27.
 */
public class MyLink {
    Node head = null;  //头节点

    /**
     * 链表中的节点,data表示数据,next是下个节点的引用
     */
    class Node {
        Node next = null;  //节点的引用,指向下一个节点
        int data;   //节点的对象,即内容

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

    }

    /**
     * 向链表中插入数据
     * @param d
     */
    public void addNode(int d){
        Node newNode = new Node(d);  //实例化一个节点
        if (head == null){
            head = newNode;
            return;
        }
//      /*插入到最后面*/
//        Node tmp = head;
//        while (tmp.next != null){
//            tmp = tmp.next;
//        }
//        tmp.next = newNode;
        /*插入到最前面*/
        newNode.next = head;
        head= newNode;
    }

    /**
     * 删除第index个节点
     * @param index
     * @return
     */
    public boolean deleteNode(int index){
        if (index < 1 || index > length()){
            return false;
        }
        if (index == 1){
            head = head.next;
            return true;
        }
        int i = 2;
        Node preNode = head;
        Node curNode = preNode.next;
        while (curNode != null){
            if (i == index){
                preNode.next = curNode.next;
                return true;
            }
            preNode = curNode;
            curNode = curNode.next;
            i++;
        }
        return false;
    }

    /**
     * 返回链表长度
     * @return
     */
    public int length(){
        int length = 0;
        Node tmp = head;
        while (tmp != null){
            length++;
            tmp = tmp.next;
        }
        return length;
    }



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

    public static void main(String[] args){
        MyLink list = new MyLink();
        list.addNode(5);
        list.addNode(3);
        list.addNode(1);
        list.addNode(2);
        list.addNode(6);
        list.addNode(4);
        System.out.println("linkLength:" + list.length());
        System.out.println("head.data:" + list.head.data);
        list.printList();
        list.deleteNode(2);
        list.printList();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值