單鏈表java實現
阿新 • • 發佈:2018-04-13
UC pre tostring 都是 單鏈表 ole 考試 lean ast
單鏈表java實現,基礎的東西不能忘記哦。這些都是大學的時候經常考試的
package dataStructure; import java.util.HashMap; /** * @author JESH * * @param <T> */ public class LinkList<T> { private final Node<T> head; public LinkList() { head = new Node<T>(null); } publicvoid addNode(T data) { Node<T> n = new Node<T>(data); Node<T> tmp = head; while(tmp.getNext()!=null) { tmp = tmp.getNext(); } tmp.setNext(n); } public T getData(int index) { if(index <0) {return null; } int i = 0; Node<T> tmp = head; while(tmp.getNext() != null) { if(i++ == index) { return (T) tmp.data; } tmp = tmp.getNext(); } if(i == index) {return (T) tmp.data; } return null; } public boolean delNode(T data) { if(data ==null) return false; Node tmp = head; while(tmp.getNext() != null) { if(tmp.getNext().data.equals(data)) { tmp.setNext(tmp.getNext().getNext()); return true; } tmp = tmp.getNext(); } return false; } public String toString() { StringBuffer sb = new StringBuffer(); Node t= head; sb.append("head:" + t.data); while(t.getNext()!=null) { t = t.getNext(); sb.append("-->").append("node:"+t.data.toString()); } sb.append("-->null"); return sb.toString(); } private class Node<T> { T data; private Node next = null; public Node(T data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } } public static void main(String[] args) { LinkList<Integer> ll = new LinkList<Integer>(); for(int i = 0;i<100;i++) { ll.addNode(i); } for(int j =0;j<108;j++) { System.out.println(ll.getData(j)); } for(int j =0;j<108;j++) { if(j%3==0) { ll.delNode(j); } } System.out.println(ll); LinkList<HashMap<String,String>> l2 = new LinkList<HashMap<String,String>>(); System.out.println(l2); HashMap m = new HashMap<String,String>(); m.put("1", "1"); l2.addNode(m); System.out.println(m); System.out.println(l2); System.out.println(l2.getData(0)); System.out.println(l2.getData(1)); System.out.println(l2.getData(2)); System.out.println(l2.getData(4)); System.out.println(l2.getData(5)); l2.delNode(m); System.out.println(l2); } }
單鏈表java實現