使用java实现单链表----(java中的引用就是指针)

//一直以为java中没有指针,其实java的引用就是指针,只不过堆栈中的引用储存了在堆中的地址,可以看做java中的指针。
public class sibgleLink<E> { // 结点内部类 private class Node { private Object data; private Node next = null; public Node() { data = null; } // 带数据的构造函数 public Node(E data) { this.data = data; } } private Node head; // 头引用(指针) private Node rear; // 尾引用(指针) private Node point; // 临时引用(指针) private int length = 1; // 链表长度 // 带参数的构造函数 public sibgleLink(E e) { head = new Node(); head.data = e; rear = head; length = 1; } // 尾插法 public void add(E elem) { point = new Node(elem); rear.next = point; rear = point; length++; } // 遍历节点 public void traverse() { point = head; // 移动临时引用到头结点 if (head != null) System.out.print("[" + head.data + "]"); while (point.next != null) { System.out.print("->[" + point.next.data + "]"); point = point.next; } System.out.println(); } // 返回长度 public int length() { return this.length; } // 清除 public boolean clear() { while (head.next.next != null) { head.next = head.next.next; } head.next = null; rear = head; point = null; length = 1; return true; } // 插入元素 public boolean insert(int x, E data) { // 工作节点 point = head; int wz = 1; if (x == 1) { Node n = new Node(data); n.next = head; head = n; length++; return true; } if (x < 1 || x > this.length) { return false; } else { while (point.next != null && wz < x - 1) { point = point.next; wz++; } // 放入一个节点 Node n = new Node(data); n.next = point.next; point.next = n; length++; return true; } } // 删除 public boolean del(int x) { point = head; int wz = 1; if (x < 0 || x > length) { return false; } else if (x == length) { point = head; while (point.next != null) { point = rear; point.next = null; length--; } } else { while (point.next != null && wz < x - 1) { point = point.next; wz++; } Node d = point.next; point.next = point.next.next; d = null; return true; } return false; } // 更改 public boolean change(int x, E data) { point = head; int wz = 1; if (x < 0 || x > length) { return false; } else { while (point.next != null && wz < x) { point = point.next; wz++; } point.data = data; return true; } } // 移动指针 private Node movePoint(int position) { if (position < 0) return head; if (position > length) return rear; if (position >= 0 && position <= length) { point = head; while (point != null) { if (position == 0) break; position--; point = point.next; } } return point; } public E find(int position) { if (position >= 0 && position < length) { Node tmp = movePoint(position); return (E) tmp.next.data; } return null; } // test public static void main(String[] args) { sibgleLink<Integer> si = new sibgleLink<Integer>(0); si.add(5); si.add(6); si.insert(2, 2); si.traverse(); si.del(3); si.traverse(); si.change(3, 77); si.traverse(); System.out.println(si.length()); } }

  结果:

[0]->[2]->[5]->[6]
[0]->[2]->[6]
[0]->[2]->[77]
4

  

原文地址:https://www.cnblogs.com/zhongyimeng/p/9945332.html