5.给定两个单向链表,计算两个链表的第一个公共节点,若没有公共节点,返回空。
int CalcLength(SNode *p){
int nLen = 0;
while (p){
p = p->pNext;
nLen++;
}
return nLen;
}
SNode *FindFirstSameNode(SNode *pA, SNode *pB){
pA = pA->pNext;
pB = pB->pNext;
int nA = CalcLength(pA);
int nB = CalcLength(pB);
if (nA > nB){
swap(pA, pB);
swap(nA, nB);
}
for (int i = 0; i < nB - nA; i++)
pB = pB->pNext;
while (pA){
if (pA == pB)
return pA;
pA = pA->pNext;
pB = pB->pNext;
}
return NULL;
}
6.拓扑排序,结点数为n,用邻接矩阵graph[n][n]存储边权,用indegree[n]存储每个结点的入度
void topologic(int *toposort){
int cnt = 0;
queue<int> q;
int i;
for (i = 0; i < n; i++){
if(indegree[i] == 0)
q.push(i);
}
int cur;
while(!q.empty()){
cur = q.front();
q.pop();
toposort[cnt++] = cur;
for(i = 0; i < n; i++){
if (graph[cur][i] != 0){
indegree[i]--;
if(indegree[i] == 0)
q.push(i);
}
}
}
}