1.1数组(Array)
三种语言的声明方式:
java,C++: int a[1024];
Python: list= []
JavaScript: let x = [1, 2, 3]
1.2基本操作及时间复杂度:
删除和插入一个元素平均需要n/2个元素,所以时间复杂度都为O(n)
删除元素 | O(n) |
添加元素 | O(n) |
随机访问某个元素 | O(1) |
1.2.1数组Java版源码(ArryList)
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
{
......
}
传容量的构造函数(ArryList类中还有若干重载的构造函数):
public ArrayList(int capacity)
{
// Must explicitly check, to get correct exception.
if (capacity < 0)
throw new IllegalArgumentException();
data = (E[]) new Object[capacity];
}
1.2.2容量扩增机制
从下面这段代码中可以看出,如果向数组中添加元素超出了定义时申请的容量,数组会自动扩充为原来的两倍容量
public void ensureCapacity(int minCapacity)
{
int current = data.length;
if (minCapacity > current)
{
E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
}
TODO:C++ STL中的源码
2.链表(LinkedList)
2.1简介
2.2分类:
- 单链表
- 双向链表(double linked list)
- 循环单链表
- 循环双向链表
2.3 java示例代码
import java.io.*;
// Java program to implement
// a Singly Linked List
public class LinkedList {
Node head; // head of list
// Linked list Node.
// This inner class is made static
// so that main() can access it
static class Node {
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
// Method to insert a new node
public static LinkedList insert(LinkedList list, int data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
// Return the list by head
return list;
}
// Method to print the LinkedList.
public static void printList(LinkedList list)
{
Node currNode = list.head;
System.out.print