线性表概述及单向链表实现
1. 线性表的定义:
零个或多个数据元素的有限序列。
2. 在复杂的线性表中,一个数据元素可以由若干个数据项组成。
3. 线性表的顺序存储结构:
用一段地址连续的存储单元依次存储线性表的数据元素。
顺序存储结构需要三个属性:存储空间的起始位置、线性表的最大存储容量、线性表的当前长度。
顺序存储结构的增、删、改、查。
线性表顺序存储结构的优缺点:
优点:无须为表示表中元素之间的逻辑关系而增加额外的存储空间。可以快速地存取表中的任一位置的元素。
缺点:插入和删除操作需要移动大量的元素。当线性表长度变化较大时,难以确定存储空间的容量。当线性表长度变化较大时,难以确定存储空间的容量。造成存储空间“碎片”。
4. 线性表的链式存储结构:
用一组任意的存储单元存储线性表的数据元素,这组存储单元可以是连续的,也可以是不连续的。
结点包括数据域和指针域。数据域用来存储数据元素信息。指针域用来存储直接后继位置。
优点:对于插入或删除越频繁的操作,链式存储结构的线性表的效率优势越明显。
5. 线性表的顺序存储结构和链式存储结构的优缺点:
(1) 在存储分配方式上:顺序存储结构用一段连续的存储单元依次存储线性表的数据元素。链式存储结构用一组任意的存储单元存放线性表的元素。
(2)时间性能:
查找:顺序存储结构:;链式存储结构:。
插入和删除:顺序存储结构需要平均移动表长一半的元素,时间为,而链式存储结构插入时间为。
(3)空间性能:顺序存储结构需要预先分配存储空间,大了浪费,小了易溢出。而链式存储结构不需要分配存储空间,只要有就可以分配,元素个数也不受限制。
如何使用?
当需要频繁查找,很少插入和删除操作时宜采用顺序存储结构。当需要频繁插入和删除时,宜采用链式存储结构。当线性表中的元素个数变化较大或根本不知道有多大时,最好使用链式结构。
6. 静态链表:
用数组描述的链表,叫静态链表。
静态链表的优缺点:
优点:在插入和删除操作时,只需要修改游标,不需要移动元素,从而改进了在顺序存储结构中的插入和删除操作需要移动大量元素的缺点。
缺点:没有解决连续存储分配带来的表长难以确定的问题。失去了顺序存储结构随机存取的特性。
7. 循环链表
当尾结点的指针指向头结点时,该链表就是循环链表。
8. 双向链表:
在单链表中将每个结点的再设置一个指向其前驱结点的指针域的链表。
单向链表
public classNode {
//数据域
public long data;
//指针域
public Node next;
public Node(long value) {
this.data = value;
}
public void display() {
System.out.print(data +" ");
}
}
public classLinkList {
//头结点
private Nodefirst;
public LinkList() {
first = null;
}
public void insertFirst(long value) {
Node node = new Node(value);
node.next = first;
first = node;
}
public Node deleteFirst() {
Node tmp = first;
first = tmp.next;
return tmp;
}
public void display() {
Node current = first;
while(current !=null) {
current.display();
current= current.next;
}
System.out.println();
}
public Node find(long value) {
Node current = first;
while(current.data != value) {
if(current.next ==null) {
returnnull;
}
current= current.next;
}
return current;
}
public Node delete(long value) {
Node current = first;
Node previous = first;
while(current.data!= value) {
if(current.next ==null) {
returnnull;
}
previous= current;
current= current.next;
}
if(current ==first) {
first = first.next;
}else{
previous.next = current.next;
}
return current;
}
}
public classTestLinkList {
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insertFirst(34);
linkList.insertFirst(23);
linkList.insertFirst(12);
linkList.insertFirst(0);
linkList.insertFirst(-1);
// linkList.display();
//
// linkList.deleteFirst();
// linkList.display();
//
// Nodenode = linkList.find(23);
// node.display();
Node node1 = linkList.delete(0);
node1.display();
System.out.println();
linkList.display();
}
}
运行结果:
-1 12 23 34