引言
2020阿里巴巴专家组出题,等你来答:
题目:如何判断两个链表是否相交
出题人:阿里巴巴新零售技术质量部
参考答案:
$O(n^2)$: 两层遍历,总能发现是否相交
$O(n)$: 一层遍历,遍历完两个链表,如果两个链表的最后一个结点指针相同,则相交,否则不相交
题目:一颗现代处理器,每秒大概可以执行多少条简单的MOV指令,有哪些主要的影响因素?
出题人:阿里巴巴出题专家:子团/创新产品虚拟化&稳定性资深技术专家
参考答案:
及格: 每执行一条mov指令需要消耗1个时钟周期,所以每秒执行的mov指令和CPU主频相关。
加分: 在CPU微架构上,要考虑数据预取,乱序执行,多发射,内存stall(前端stall和后端stall)等诸多因素,因此除了cpu主频外,还和流水线上的效率(IPC)强相关,比较复杂的一个问题。
题目:如何实现一个高效的单向链表逆序输出?
出题人:阿里巴巴出题专家:昀龙/阿里云弹性人工智能负责人
参考答案:下面是其中一种写法,也可以有不同的写法,比如递归等。供参考。
typedef struct node{
int data;
struct node* next;
node(int d):data(d), next(NULL){}
}node;
void reverse(node* head)
{
if(head == NULL){
return;
}
node* pleft = NULL;
node* pcurrent = head;
node* pright = head->next;
while(pright){
pcurrent->next = pleft;
node *ptemp = pright->next;
pright->next = pcurrent;
pleft = pcurrent;
pcurrent = pright;
pright = ptemp;
}
while(pcurrent != NULL){
cout<< pcurrent->data << "\t";
pcurrent = pcurrent->next;
}
}
class Solution<T> {
public void reverse(ListNode<T> head) {
if (head == null || head.next == null) {
return ;
}
ListNode<T> currentNode = head;
Stack<ListNode<T>> stack = new Stack<>();
while (currentNode != null) {
stack.push(currentNode);
ListNode<T> tempNode = currentNode.next;
currentNode.next = null; // 断开连接
currentNode = tempNode;
}
head = stack.pop();
currentNode = head;
while (!stack.isEmpty()) {
currentNode.next = stack.pop();
currentNode = currentNode.next;
}
}
}
class ListNode<T>{
T val;
public ListNode(T val) {
this.val = val;
}
ListNode<T> next;
}