1.寻找单链表倒数第K个节点。
Node* find_k(PLink phead, int k)
{
Node* pfast = phead->pnext;
Node* pslow = pfast;
for (int i = 0; i < k - 1; ++i)
{
pfast = pfast->pnext;
}
while (pfast->pnext != NULL)
{
pfast = pfast->pnext;
pslow = pslow->pnext;
}
return pslow;
}
2.只给定单链表的某个节点P,
p不是尾结点(//p->next != NULL),删除该节点
void DeletePoint(Node* pCur)
{
Node* pDelete = pCur->pnext;
pCur->mdata = pDelete->mdata;
pCur->pnext = pDelete->pnext;
free(pDelete);
}
3.单链表只给定一个节点p,在p之前插入一个数据val。
int InsertFront(Node* p, ELEM_TYPE val)
{
Node* pnewnode = (Node*)malloc(sizeof(Node));
if (pnewnode == NULL)
{
return 0;
}
pnewnode->pnext = p->pnext;
p->pnext = pnewnode;
pnewnode->mdata = p->mdata;
p->mdata = val;
return 1;
}
4.判断两个链表是否相交,如果相交,找出交点
Node* Intersect(PLink phead1, PLink phead2)
{
Node* pCur1 = phead1;
Node* pCur2 = phead2;
int len1 = 0;
int len2 = 0;
while (pCur1->pnext != NULL)
{
pCur1 = pCur1->pnext;
len1++;
}
while (pCur2->pnext != NULL)
{
pCur2 = pCur2->pnext;
len2++;
}
if (pCur1 == pCur1)
{
int k = abs(len1 - len2);
pCur1 = (len1 - len2) > 0 ? phead1 : phead2;
pCur2 = (len1 - len2) <= 0 ? phead1 : phead2;
for (int i = 0; i < k; ++i)
{
pCur1 = pCur1->pnext;
}
while (pCur1 != NULL)
{
if (pCur1 == pCur2)
{
return pCur1;
}
pCur1 = pCur1->pnext;
pCur2 = pCur2->pnext;
}
}
return NULL;
}
5.找单链表的中间节点,只允许遍历一次。
Node* Find_Middle_Node(PLink phead)
{
Node* pfast = phead->pnext;
Node* pslow = pfast;
while (pfast != NULL && pfast->pnext != NULL)
{
pfast = pfast->pnext->pnext;
pslow = pslow->pnext;
}
return pslow;
}
6.从尾到头打印单链表
1.不能破坏单链表结构
2.不能使用栈
(递归)
void PrintR(PLink node)
{
if (node == NULL)
{
return;
}
PrintR(node->pnext);
printf("%d ", node->mdata);
}
void PrintReverse(PLink phead)
{
Node* pfirst = phead->pnext;
PrintR(pfirst);
printf("\n");
}