[第2节]数组,链表,跳表及其实际应用

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值