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();
    }
}

猜你喜欢

转载自blog.csdn.net/u010469514/article/details/77621400