链表之Java实现

2019-01-02  本文已影响2人  低吟浅唱1990

链表是一种递归的数据结构,它或者为空null,或者是指向一个节点(node)的引用,该节点含有一个泛型的元素和一个指向另一条链表的引用

//节点
public class Node<Item> {
    Item item;
    Node<Item> next;
    public Node() {
        next = null;
    }
}
Node<String> head = new  Node<String>();
Node<String> first = new  Node<String>();
Node<String> second =  new Node<String>();
Node<String> third =  new Node<String>();
head.item = "head";
first.item = "to";
second.item = "be";
third.item = "or";
head.next = first;
first.next =  second;
second.next = third;
third.next = null;
    private static void insertLink(Node<String> node,int i,String item) {
        
        int j = 0;
        Node<String>current;
        while(node != null && j<i){
            node = node.next;
            ++j;
        }
        System.out.println("-----"+j);
        if (node == null || j>i) {
            return;
        }
        current = new Node<>();
        current.item = item;
        current.next = node.next;
        node.next = current;
        
    }
private static String getElem(Node<String> lNode,int i) {
        
        Node<String> l = lNode;
        int j = 0;
        while(l != null && j<i){
            l = l.next;
            ++j;
        }
        if (l ==null || j>i) {
            return "没有数据";
        }
        String item = l.item;
        return item;
    }
上一篇 下一篇

猜你喜欢

热点阅读