重拾单链表

参考:

  数据结构(C语言描述)  严蔚敏 吴伟民 编著

  实用数据结构教程 Java语言描述  周大庆 编著

单链表是线性表(逻辑结构)的一种链式存储表示(存储结构)

线性表是n个数据元素的有限序列。

链式表示不要求逻辑上相邻的元素在物理(存储)位置上也相邻。

线性表顺序存储结构

特点:借助元素在存储器中的相对位置(即,物理位置相邻)来表示数据元素之间的逻辑关系。

缺点: 

   插入、删除时,需移动大量数据。 

   一次性分配内存空间。 

   表的容量难以扩充。

链式存储结构是计算机中的另一种最基本和最主要的数据存储结构。 和顺序存储结构不同, 初始时链式存储结构为空链, 每当有新的数据元素需要存储时用户向系统动态申请所需的存储空间插入链中。
 
单链表每个结点有两个域,其中存储数据元素信息的域称为整数域;存储直接后继存储位置的域称为指针域。

下面写个单链表插入元素、删除元素的算法并测试。

单链表类:


public class SLL {
// 内部节点类
private static class SLLNode {
private String data;
private SLLNode next;

public SLLNode(String data) {
this.data = data;
}

public String toString() {
return data;
}
}
private SLLNode root;
private int count;

public SLLNode getRoot() {
return root;
}


public void setRoot(SLLNode root) {
this.root = root;
}


public int getCount() {
return count;
}


public void setCount(int count) {
this.count = count;
}


public void insert(String data) {
SLLNode node = new SLLNode(data);
if(this.isEmpty()) {
root = node;
count++;
} else {
SLLNode newNode = root;
while(newNode.next != null) { // 找到链表最后一个元素,从头结点开始查找
newNode = newNode.next;
}
newNode.next = node;
count++;
}
}

public void delete(SLLNode node) {
if(this.isEmpty()) {
System.out.println("空链表,不能删除");
return;
} else {
SLLNode newNode = root;
while(newNode.next != node) { // 找到要删除节点的前一个元素
newNode = newNode.next;
}
newNode.next = node.next; // 断开引用,删除node节点
count--;
}
}

public int size() {
return this.count;
}


public boolean isEmpty() {
return root == null;
}

public String toString() {
SLLNode curr = root;
while(curr.next != null) {
System.out.print(curr.data + "->");
curr = curr.next;
}
System.out.print("null");
return null;
}
}

 

测试类:


public class SLLTest {
public static void main(String[] args) {
SLL s = new SLL();
s.insert("a");
s.insert("d");
s.insert("b");
s.insert("c");
System.out.println(s.size());
System.out.println(s.getRoot());
s.toString();
}
}

 

问题:如何在测试类中获得SLLNode(节点类)实例化对象(反射 私有静态内部类)

 

 

原文地址:https://www.cnblogs.com/zhangpeng201211/p/2410976.html