Array
操作 | 时间复杂度 |
---|---|
查找第K个 | O(1) |
插入 | O(N) |
删除 | O(N) |
Linked List
操作 | 时间复杂度 |
---|---|
查找第K个 | O(N) |
插入 | O(1) |
删除 | O(1) |
数据结构:
结点内部存放数据和下一个结点的指针,结点没有名字,只能通过指针访问。(有名字的是结点的指针)
结点两种方法可行
typedef struct Node* Nodeptr;
struct Node{
int element;
Nodeptr next;
};
struct Node{
int element;
struct Node* next;
};
Node* next是错误的。
因为Node只是一个数据结构,并不是该结构的名称。因此,用struct Node 作为该结构的名称。
typedef 只是把左侧的类型重新命名,可以把struct Node叫做node类型,这样是可以的。
使用时只能得到结点的指针。因此所有对于列表的操作都是指针操作。不涉及结点本身。
列表结点不会因为删除而消失,只是删除了指向它的指针,导致无法访问这个结点了。
申请内存的时候:
Nodeptr head = (Nodeptr)malloc(sizeof(struct Node));
这是最正宗的写法,如果写为sizeof(Nodeptr),有时候也不会报错,但是其实是错的,malloc的意义是申请内存,返回指向这个内存的指针。
注意为了方便删除头节点,列表会自带一个dummy head 空头,不放数据。相当于是指向这个列表的一个指针。
Cursor Implementation of Linked Lists
数组实现列表
一个数组元素起码包含2个数据,element 和 next
element是本身的数据,next是下一个结点的index
struct ListNode{
int element;
int next
};
node[i].next是该元素下一个元素的索引值
node[i].element是该元素的数据
如果在索引是k的结点后面插入一个结点,新结点的索引是n
p = node[k].next//记录下该结点后面一个结点的索引
node[k].next = n//把k后面一个结点变为n
node[n].next = p //原来k的后面一个结点放在n后面
由于缺少内存管理,array很快就会满。
题目
1.For a sequentially stored linear list of length N, the time complexities for deleting the first element and inserting the last element are O(1) and O(N), respectively.
liner list 线性表=一种概念,即序列,可以用数组和链表实现,sequentiantlly表示顺序存储,即数组,删第一个是O(N)(所有元素向前移动一个),删最后一个是O(1),F
2.If a linear list is represented by a linked list, the addresses of the elements in the memory must be consecutive.
列表内存连续,线性表内存不连续,用列表表示线性表,内存不一定连续。F
3.If a linear list is represented by a 1-dimensional array, the addresses of the elements in the memory must be consecutive.
第二题的姊妹题,注意数组的内存一定是连续的,选T
4.If the most commonly used operations are to visit a random position and to insert and delete the last element in a linear list, then which of the following data structures is the most efficient?
A.doubly linked list
B.singly linked circular list
C.doubly linked circular list with a dummy head node
D.sequential list
随机访问index所在元素和删除最后一个,线性表更快。D
5.To merge two singly linked ascending lists, both with N nodes, into one singly linked ascending list, the minimum possible number of comparisons is:
A.1
B.N
C.2N
D.NlogN
很怪的一题,显然是把一个接到另一个后面,即一张表的尾元素小于另一张表的首元素,最小比较一次。但是可能题目的意思是通常情况,从List1的第一个从List2的第一个比到最后一个,O(N)。B
6.To delete p from a doubly linked list, we must do:
A.p->next=p->prior->prior; p->prior=p->next->next;
B.p->prior->next=p->next; p->next->prior=p->prior;
C.p->next->prior=p; p->next=p->next->next;
D.p->prior=p->prior->prior; p->prior->next=p;
p是要删掉的,如果把p直接赋值的肯定不对。C,D就错了,A显然有问题。