第一步:定義一個List介面,規定一些基本操作
package my.stack;public class Node<T> {private T data;private Node<T> next;public Node(){data = null;next = null;}public Node(T data){this.data = data;this.next = null;}public Node(T data, Node<T> next){this.data = data;this.next = next;}public void setData(T data){this.data = data;}public T getData(){return this.data;}public void setNext(Node<T> next){this.next = next;}public Node<T> getNext(){return this.next;}}
第二步:實現該介面定義的函數
1)由於是鏈表,首先要定義一個節點類(可以作為內部類實現)
package my.list;public class Node<T> {private T data;private Node<T> next;public Node(){data = null;next = null;}public Node(T data){this.data = data;this.next = null;}public Node(T data, Node<T> next){this.data = data;this.next = next;}public void setData(T data){this.data = data;}public T getData(){return this.data;}public void setNext(Node<T> next){this.next = next;}public Node<T> getNext(){return this.next;}}
2)實現介面
package my.list;public class MyLinkedList<T> implements MyList<T> {private Node<T> head;private Node<T> tail;private int size;public MyLinkedList(){this.head = null;this.tail = null;this.size = 0;}public MyLinkedList(T data){this.head = new Node<T>(data);this.tail = null;this.size = 0;}@Override//添加元素public void add(T element) {Node<T> node = new Node<T>(element);if(this.head == null){this.head = node;this.tail = node;}else{this.tail.setNext(node);this.tail = node;}this.size++;}@Override//清空鏈表public void clear() {this.head = null;this.tail = null;System.gc();}@Override//刪除鏈表最後一個節點public int delete() {Node<T> point = head;while(point.getNext() != this.tail){point = point.getNext();}tail.setNext(null);tail = point;size--;return 0;}@Overridepublic boolean delete(int location) {if(location > size-1){System.out.println("out of range");}else{Node<T> point = head;int count = 1;while(point.getNext() != this.tail){point = point.getNext();count++;if(count == location){System.out.println("finl this element:"+point.getData());}break;//Node<T> temp = point.getNext();//point.setData(temp.getData());//point.setNext(temp.getNext());//temp = null;}Node<T> temp = point.getNext();point.setData(temp.getData());point.setNext(temp.getNext());temp = null;return true;}return false;}@Override//尋找鏈表中是否包含某元素public boolean find(T element) {// TODO Auto-generated method stubNode<T> point = head;while(point.getNext() != null){if(point.getData().equals(element)){return true;}point = point.getNext();}return false;}@Overridepublic int size() {return this.size;}}
第三部:編寫用戶端進行測試
此處暫未實現使用location位置進行查詢,鏈表隨即查詢效率較低
package my.list;public class MyLinkedListClient {public static void main(String[] args){//System.out.println("hello world");//Node<String> node = new Node<String>("hello");//MyLinkedList<Node<String>> list = new MyLinkedList<Node<String>>();MyLinkedList<String> list = new MyLinkedList<String>();list.add("1");list.add("2");list.add("3");list.add("4");list.add("5");//list.delete();System.out.println(list.size());//System.out.println(list.delete(2));//list.clear();//list.clear();}}