链表的笔试题

单向链表节点定义

typedef struct node
{
    int data;
    struct node *next;
}Node,*pNode;
双向链表节点定义

typedef struct node
{
    int data;
    struct node *next;
    struct node *pre;
}Node,*pNode;

链表逆序

非递归方法:

pNode RevertList(pNode head)
{
    if ((head == NULL) || (head->next == NULL))
        return head;
    pNode p1 = head;
    pNode p2 = p1->next;
    pNode p3 = p2->next;
    p1->next = NULL;
    while(p3 != NULL)
    {
        p2->next = p1;
        p1 = p2;
        p2 = p3;
        p3 = p3->next;
    }
    p2->next = p1;
    head = p2;
    return head;
}
递归方法:

pNode RevertList(pNode head)
{
    pNode p1 = NULL;
    if ( (head == NULL) || (head->next == NULL))
        return head;

    p1 = RevertList(head->next);
    head->next->next = head;
    head->next = NULL;
    return p1;
}

将2个有序的链表合并成一个有序链表

非递归方法:

pNode MergeList(pNode head1, pNode head2)
{
    if (head1 == NULL)
        return head2;
    if (head2 == NULL)
        return head1;

    pNode p1 = NULL;
    pNode p2 = NULL;
    pNode head = NULL;
    if (head1->data < head2->data)
    {
        head = head1;
        p1 = head1->next;
        p2 = head2;
    }
    else
    {
        head = head2;
        p1 = head1;
        p2 = head2->next;
    }
    pNode curNode = head;
    while((p1 != NULL) && (p2 != NULL))
    {
        if (p1->data < p2->data)
        {
            curNode->next = p1;
            curNode = p1;
            p1 = p1->next;
        }
        else
        {
            curNode->next = p2;
            curNode = p2;
            p2 = p2->next;
        }
    }
    if (p1 == NULL)
        curNode->next = p2;
    else
        curNode->next = p1;

    return head;
}
递归方法:

pNode MergeList(pNode head1, pNode head2)
{
    if (head1 == NULL)
        return head2;
    if (head2 == NULL)
        return head1;

    pNode head = NULL;
    if (head1->data < head2->data)
    {
        head = head1;
        head->next = MergeList(head1->next, head2);
    }
    else
    {
        head = head2;
        head->next = MergeList(head1, head2->next);
    }
    return head;
}

判断一个单链表是有环的

bool CheckLoop(const pNode head)
{
    if (head == NULL)
        return false;
    pNode low = head;
    pNode fast = head->next;

    while((fast != NULL) && (fast->next != NULL))
    {
        if (low == fast)
            return true;
        low = low->next;
        fast = fast->next->next;
    }
    return false;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值