Linked list
单恋表(^_^)
数组是由一系列相同数据类型,而且占用了连续的存储空间。
优点
- 因为是连续的地址,查找方便,通过索引。
缺点
- 进行删除或添加元素时,牵一发而动全身。
- 以一开始定义一个数组的时候,就会限制该数组元素的个数。
单链表是线性数据结构,存储时不必连续的存储在一起,彼此通过pointers相互连接。
优点
- 删除或添加元素时,高效
- 可以随时添加元素,没有上限
缺点
- 不能随机访问,需要通过头结点,挨家挨户的去查找所找的元素,也不能使用binary search
- 因为包含 pointer & data,pointer 占用资源
- Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists,简单来说就是没有数组的“索引”
先上C代码
1 #include<stdlib.h> 2 #include<stdio.h> 3 4 struct node 5 { 6 int data; 7 struct node * next; 8 }; 9 void printList(struct node * n) 10 { 11 while(NULL != n) 12 { 13 printf("%d\t", n->data); 14 n = n->next; 15 } 16 17 } 18 int main(void) 19 { 20 struct node * frist = NULL; 21 struct node * second = NULL; 22 struct node * third = NULL; 23 24 frist = (struct node *)malloc(sizeof(struct node)); 25 second = (struct node *)malloc(sizeof(struct node)); 26 third = (struct node *)malloc(sizeof(struct node)); 27 28 frist->data = 1; 29 frist->next = second; 30 31 second->data = 2; 32 second->next = third; 33 34 third->data = 3; 35 third->next = NULL; 36 37 printList(frist); 38 return 0; 39 }
Java代码
1 package bird; 2 3 public class LinkedList { 4 Node node; 5 6 static class Node{ 7 8 Node next; 9 int data; 10 Node(int data){ 11 this.data = data; 12 next = null; 13 } 14 } 15 16 static void printList(Node n) { 17 while(null != n) { 18 System.out.println("data: "+n.data); 19 n = n.next; 20 } 21 } 22 23 public static void main(String[] args) { 24 LinkedList head = new LinkedList(); 25 26 head.node = new Node(1); 27 Node second = new Node(2); 28 Node third = new Node(3); 29 30 head.node.next = second; 31 second.next = third; 32 33 printList(head.node); 34 } 35 }