《Java数据结构与算法》笔记-CH5-链表-2单链表,增加根据关键字查找和删除

 /**
* Link节点 有数据项和next指向下一个Link引用
*/
class Link {
private int iData;// 数据
private double dData;// 数据
public Link next;// 下一个link节点的引用 public int getiData() {
return iData;
} public Link(int i, double d) {
iData = i;
dData = d;
} public String toString() {
return "[" + iData + "," + dData + "]";
} public void displayLink() {
System.out.println(toString());
}
} /**
* 链表类 维护一个头节点
*/
class LinkList {
private Link first; /**
* 初始化的时候头结点置空
*/
public LinkList() {
first = null;
} /**
* 头结点是空代表链表为空
*
* @return
*/
public boolean isEmpty() {
return first == null;
} /**
* 向链表头插入Link节点
*
* @param link
*/
public void insertFirst(Link link) {
link.next = first;// 要插入的节点的next指针指向链表的头节点
first = link;// 链表的头结点指向被插入的节点
} /**
* 从链表头删除头结点并返回
*
* @return
*/
public Link deleteFirst() {
Link temp = first;// temp临时存上头结点
first = first.next;// 将头节点的next指针指向下一个节点
return temp;// 返回temp
} @Override
public String toString() {
if (isEmpty())
return "{}";
StringBuilder sb = new StringBuilder();
sb.append("{");
Link current = first;
while (current != null) {
sb.append(current.toString());
sb.append(",");
current = current.next;
}
sb.deleteCharAt(sb.length() - 1);
sb.append("}");
return sb.toString();
} /**
* 根据key寻找节点
*
* @param key
* @return
*/
public Link find(int key) {
Link curr = first;
while (curr.getiData() != key) {
if (curr.next == null)
return null;
else
curr = curr.next;
}
return curr;
} /**
* 根据key值删除节点
*
* @param key
* @return
*/
public Link deleteByKey(int key) {
Link current = first;
Link previous = first;
// 根据key值遍历
while (current.getiData() != key) {
if (current.next == null)//找不到,返回null
return null;
else {
previous = current;
current = current.next;
}
}
//找到,此时头结点就是要删除的节点,直接把头结点置为头结点的next节点
if (current == first)
first = first.next;
else//找到,此时把前一个节点的next指向当前节点的next即可
previous.next = current.next;
return current;
} public void displayList() {
System.out.println(toString());
}
} public class LinkListDemo {
public static void main(String[] args) {
LinkList ll = new LinkList();
for (int i = 0; i < 10; i++) {
Link l = new Link(i, i + 11.23);
ll.insertFirst(l);
ll.displayList();
}
ll.deleteFirst();
ll.deleteFirst();
ll.displayList();
Link l3 = ll.find(3);
System.out.println("key 为3的节点是: "+l3.toString());
ll.deleteByKey(3);
System.out.print("删除该节点后,链表是:");
ll.displayList();
}
}
上一篇:《Java数据结构与算法》笔记-CH5-链表-3双端链表


下一篇:python:redis简单操作