#include<iostream>
using namesapce std;
struct Node{
DataType data;
Node* next;
};
//链表逆序输出(不改变链表)
void ReversePrint(Node*pHead)
{
if(pHead==NULL)
return ;
if(pHead->next!=NULL)
{
ReversePrint(pHead->next);
}
cout<<pHead->data<<"";
}
//链表逆置
Node* Reverse(Node*pHead)
{
if(pHead==NULL)
return NULL;
Node*cur=pHead;
Node*prev=NULL;
Node*next=cur->next;
while(cur!=NULL)
{
cur->next=prev;
prev=cur;
cur=next;
if(cur!=NULL)
cur=cur->next;
}
return prev;
}
//链表判环
//设置两个指针,一个一次走一个,一个一次走两,如果两个指针相遇则存在环
Node*MeetingNode(Node*pHead)
{
if(pHead==NULL)
return NULL;
Node*slow=pHead->next;
Node* fast=slow->next;
while(slow&&fast)
{
if(slow==fast)
return fast;
slow=slow->next;
fast=fast->next;
if(fast!=NULL)
fast=fast->next;
}
return NULL;
}
//环求长度,如果链表存在环,两个指针在相遇点,在走一遍,做记录,即求出环的长度
int length(Node*pHead,int count)
{
if(pHead==NULL)
return NULL;
Node*MeetNode=MeetintNode(pHead);
if(MeetNode==NULL)
return NULL;
int count=1;
Node*cur=MeetNode;
if(cur->next!=NULL)
{
cur=cur->next;
++count;
}
return count;
}
//链表求环的入口点,定义两个从头开始的指针,一个先走环的长度,然后两个指针同时走,将会在入口处汇合
Node* EntryNodeOfLoop(ListNode* pHead)
{
Node*fast==pHead;
Node*last==pHead;
while(count--)
{
fast=fast->next;
}
while(fast!=last)
{
fast=fast->next;
last=last->next;
}
return last;
}
//找出链表倒数第k个节点,设置两个指针,第一个指针先走k-1,然后两个指针同时走,当第一个指针的next为空时,第二个指针则指向倒数第k个节点
Node*FindkthToTail(Node*pHead,unsigned int k)
{
if(pHead==NULL||k==0)//防止头指针为空以及k为0
return NULL;
Node*fast=pHead;
Node*slow=NULL;
for(unsigned int i=0;i<k-1;++i)
{
if(fast->next!=NULL)//如果链表节点数小于k
fast=fast->next;
else
{
return NULL;
}
}
slow=pHead;
while(fast->next!=NULL)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
//合并两个有序链表,合并后依然有序
Node*Merge(Node*pHead1,Node*pHead2)
{
if(pHead1==NULL)
return pHead2;
else if(pHead2==NULL)
return pHead1;
Node* Head=NULL;
if(pHead1->val<pHead->val)
{
Head=pHead1;
Head->next=Merge(pHead1->next,pHead2);
}
else
{
Head=pHead2;
Head->next=Merge(pHead1,pHead2->next);
}
return Head;
}
单链表的部分面试题
最新推荐文章于 2022-08-27 16:11:02 发布