1、单向链表
实现思路:创建Node类,包括自己的数据和指向下一个;创建Node类,包括头尾节点,实现添加、删除、输出等功能。
tips:n = n.next不破坏链表结果,而n.next = n.next.next就等于是n节点的next属性变成了再下一个,即指向n+1个节点的指针丢失,但实际上n+1节点仍在,只不过从链表中去除。
具体代码:
public class NodeList<Integer> { class Node<Integer> { Node<Integer> next = null; //指向下一节点 Integer data; //节点所存数据 //Node类构造方法 public Node(Integer d) { this.data = d; } } Node<Integer> head; //链表的头节点 Node<Integer> last; //链表的尾节点 int length; //链表长度 //链表的无参构造方法 public NodeList() { this.head = new Node<Integer>(null); //头节点为空 } //创建链表的同时添加第一个数据 public NodeList(Integer d) { this.head = new Node<Integer>(d); this.last = head; //此时头尾节点一样 length++; } //尾部添加节点 public void add(Integer d) { if (head == null) { head = new Node<Integer>(d); last = head; length++; } else { Node<Integer> newNode = new Node<Integer>(d); last.next = newNode; //令之前的尾节点指向新节点 last = newNode; //新节点成为尾节点 length++; } } //删除指定数据 public boolean del(Integer d) { if (head == null) { return false; } Node<Integer> n = head; //从头开始判断 if (n.data == d) { head = head.next; length--; return true; } while (n.next != null) { if (n.next.data == d) { n.next = n.next.next; //n节点指向了n+2节点 length--; return true; } n = n.next; //正常移动不破坏链表 } return false; } public void print() { if (head == null) { System.out.println("此链表为空!"); } Node<Integer> n = head; while (n != null) { System.out.println(n.data+","); n = n.next; } } }