若要在三个函数里完成一项功能:
例如之前的"复杂链表的复制":
Main:负责测试:1>测试用例编写
2>测试数据的构造
3>测试数据打印
Solution:解决明确的问题
Node:链表的结点
**Main.java:**
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();//创建一个solution对象
testComplexListCopy(solution); //复杂链表的复制
}
private static void testComplexListCopy(Solution solution) {//复杂链表的复制,这只是测试,
//并不是具体的方法,所以不用要返回值
// 1. 构建测试数据
CNode head = createComplexList1();
// 2. 进行测试
CNode resultHead = solution.copy(head);
// 3. 对测试结果进行打印
printCList(resultHead);
}
// CNode 必须有一个构造方法,形参是 int val
// 并且,初始化后,next 和 random 都是 null
private static CNode createComplexList1() { //创建复杂链表
CNode n1 = new CNode(1);
CNode n2 = new CNode(2);
CNode n3 = new CNode(3);
CNode n4 = new CNode(4);
n1.random = n3; n2.random = n1; n3.random = n3;//手动形成random
n1.next = n2; n2.next = n3; n3.next = n4;//手动形成链表
return n1;//返回的是链表
}
// CNode 必须实现一个 String toString() 方法
private static void printCList(CNode head) {
for (CNode cur = head; cur != null; cur = cur.next) {
System.out.print(cur + " --> ");
}
System.out.println();
}
}
**Solution.java:**
public class Solution {
CNode copy(CNode head) {
if (head == null) {
return null;
}
CNode p1 = head;
while (p1 != null) {
CNode p2 = new CNode(p1.val);
p2.next = p1.next;
p1.next = p2;
p1 = p2.next;
}
p1 = head;
while (p1 != null) {
CNode p2 = p1.next;
if (p1.random != null) {
p2.random = p1.random.next;
}
p1 = p2.next;
}
p1 = head;
CNode newHead = head.next;
while (p1 != null) {
CNode p2 = p1.next;
p1.next = p2.next;
if (p2.next != null) {
p2.next = p2.next.next;
}
p1 = p1.next;
}
return newHead;
}
}
**Node.java:**
public class CNode {
int val;
CNode next = null;
CNode random = null;
CNode(int val) {
this.val = val;
}
public String toString() {
return String.format("CNode(%d)", val);
}
}
类的设计原则:
1>自顶向下设计
2>职责明确
3>一个方法完成一个明确的工作<把功能封装到方法>
4>确定哪些方法是对外的,哪些方法是对内的
5>重复的代码应该抽离到一个方法中,而不是简单的复制粘贴
##不需要依赖属性且在静态方法里可以调用,那么就写一个静态方法封装功能
顺序表最大的好处:支持随机访问(下标访问)
1>不易有内存碎片;2>对缓存更友好;3>单个数据而言,空间更节省
链表最大的好处:头尾插,头尾删,空间复杂度O(1),
1>若数据比较大,不需要预留空间
##若无特殊理由可一律用顺序表!
泛型:存储的是广泛的,不确定的类型
ArrayList<Person> arrayList;
ArrayList<元素类型名称>
ArrayList<Integer>
//保存的是int的包装类型
顺序表:ArrayList<Person> arrayList=new ArrayList<>();
链表:LinkedList<Person> linkedList=new LinkedList<>();
类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
引用类型 null
import java.util.ArrayList;
import java.util.LinkedList;
class Person{
public String name;
public int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
}
public class Main{
public static void main(String[] args){
ArrayList<Person> arrayList=new ArrayList<>();
arrayList.add(new Person("A",7));
arrayList.add(new Person("B",9));
arrayList.add(new Person("C",19));
for(int i=0;i<arrayList.size();i++){
Person p=arrayList.get(i);
System.out.println(p.name+";"+p.age);
}
for(Person p:arrayList){
System.out.println(p.name+";"+p.age);
}
}
}