单链表

 

  每条数据记录下条记录的位置

package demo2;

//单链表
public class Node {
    // 节点内容
    Object data;
    // 下一个节点
    Node next;

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

    // 为节点追加节点
    public Node append(Node next) {
        Node currentNode = this;
        // 找到最后一个节点
        while (true) {
            Node nextNode = currentNode.next();
            if (nextNode == null) {
                break;
            }
            currentNode = nextNode;
        }
        currentNode.next = next;
        return this;
    }

    // 取出下一个节点
    public Node next() {
        return this.next;
    }

    // 获取节点的数据
    public Object getData() {
        return this.data.toString();
    }

    // 判断节点是否是最后一个节点
    public boolean isLast() {
        return this.next == null;
    }

    // 删除下一个节点
    public void removeNext() {
        // 取出下下一个节点
        Node newNext = this.next.next;
        this.next = newNext;
    }

    // 显示所有节点信息
    public void show() {
        Node currentNode = this;
        while (true) {
            System.out.println(currentNode.getData());
            currentNode = currentNode.next;
            if (currentNode == null) {
                break;
            }
        }
    }

    // 插入节点作为当前节点的下一个节点
    public void insert(Node node) {
        Node nnext = next;
        this.next = node;
        node.next = nnext;
    }
}
package demo2.test;

import demo2.Node;

public class TestNode {
	public static void main(String[] args) {
		Node node = new Node("a");
		Node node1 = new Node("a1");
		Node node2 = new Node("a2");
		Node node3 = new Node("a3");

		node.append(node1).append(node2).append(node3);
//		System.out.println(node.next().next().next().getData());
//		System.out.println(node.next().next().next().next().isLast());
		node.show();
		System.out.println("-----------");
		// 删除下一个节点
		node.removeNext();
		node.show();
		System.out.println("-----------");
		//插入节点
		node2.insert(new Node("iiiii"));
		node.show();
	}
}

  

posted @ 2020-04-07 10:58  已老  阅读(88)  评论(0)    收藏  举报