数据结构之链表---单链表的实现
数据结构之链表---单链表的实现
public class Link { /** * 链结点 */ private int iData; private double dData; public Link next; public Link(int iData,double dData) { this.dData = dData; this.iData = iData; } //打印节点 public void displayLink() { System.out.println("{"+iData+","+dData+"}"); } } public class LinkList { //这个类比较简单就有一个指向节点的引用 private Link first; public LinkList() { this.first = null; } //判断链表是不是为空 public boolean isEmpty() { if(first == null) { return true; }else{ return false; } } //链表的插入头插法(面向对象的思考) public void insertFirst(Link link) { link.next = first;//首先让新生成的节点的next指向first first = link; } //删除的头节点的方法 public Link deleteFirst() { //删除节点的原理:让first指向第一个节点的下一个节点 Link temp = first; first = first.next; return temp; } //打印链表的方法 public void displayList() { Link current = first; while(current != null) { current.displayLink(); current = current.next; } System.out.println(" "); } }
查找指定链结点和删除指定的链结点:
//查找链结点 public Link find(int key) { Link current = first; while(current.dData != key) { if(current.next == null) { return null; }else{ current = current.next; } } return current; } //删除指定的链结点 public Link delete(int key) { Link current = first; Link previous = first; while(current.dData != key) { if(current.next == null)//如果遍历到最后是null { return null; }else{ //每次都让前一个引用指向当前的引用 previous = current; current = current.next; } } //如果找到该值 if(current == first)//如果当前节点是第一个节点的话,这是一种的特殊情况,因为这是由LinkList对象的first域指向的链结点而不是别的链结点的next字段所指,在这种情况下,first指向first.next就可以删除第一个链结点。 { first = first.next; }else{ previous.next = current.next; } return current; }