单链表的部分面试题


#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值