java 單鏈表的一個實現
阿新 • • 發佈:2019-09-27
package helloclean.mylink;
public class Link {
public String dataStr;
public Link next;
public Link(String dataStr) {
this.dataStr = dataStr;
this.next = null;
}
public void disPlay() {
System.out.print(" {" + dataStr + "} ");
}
}
package helloclean.mylink; /** * 單鏈表 */ public class MyLink { private Link first; public MyLink() { this.first = null; } /** * 在連結串列頭部插入, 頭插法 * @param str */ public void inserFirst(String str) { Link newLink = new Link(str); newLink.next = first; first = newLink; } public Link deleteFirst() { Link temp = first; first = first.next; return temp; } public boolean isEmpty() { return (first == null); } public Link find(String key) { Link current = first; while (!current.dataStr.equals(key)) { if(current.next == null) { return null; } else { current = current.next; } } return current; } public Link delete(String key) { Link current = first; Link previous = first; while (!current.dataStr.equals(key)) { if(current.next == null) { return null; } else { previous = current; current = current.next; } } if(current == first) { first = first.next; } else { previous.next = current.next; } return current; } public void disPlay() { System.out.print("first -> last : "); Link current = first; while (current != null) { current.disPlay(); current = current.next; } System.out.println(""); } }
package helloclean.mylink; public class App { public static void main(String[] args) { MyLink myLink = new MyLink(); myLink.inserFirst("1"); myLink.inserFirst("2"); myLink.inserFirst("3"); myLink.inserFirst("4"); myLink.disPlay(); while (!myLink.isEmpty()) { Link deleLink = myLink.deleteFirst(); System.out.print("delete:"); deleLink.disPlay(); System.out.println(); } myLink.disPlay(); } }
package helloclean.mylink;
public class Client {
public static void main(String[] args) {
MyLink myLink = new MyLink();
myLink.inserFirst("hello");
myLink.inserFirst("word");
myLink.inserFirst("x");
myLink.inserFirst("y");
myLink.inserFirst("1");
myLink.disPlay();
Link findValue = myLink.find("word");
if(null == findValue) {
System.out.println("not find link!");
} else {
System.out.println("find the link with value : " + findValue.dataStr);
}
Link deleteValue = myLink.delete("y");
if(null == deleteValue) {
System.out.println("can not delete link!");
} else {
System.out.println("delete link with key : " + deleteValue.dataStr);
}
myLink.disPlay();
}
}