笔试题汇集之链表篇(C/C++)

这篇博客介绍了C/C++中链表的一些基本操作,包括如何反转链表、在指定位置插入节点、合并两个已排序的链表以及判断链表是否有环。提供了详细的代码实现,包括递归和非递归方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//反转链表

Node* reverse_list(Node* head) {

    if(head ==NULL || head->next == NULL) {

        returnhead;

    }

    Node* p1 =head;

    Node* p2 =head->next;

    Node* p =NULL;

   head->next = NULL;

    while(p2) {

        p =p2->next;

       p2->next = p1;

        p1 = p2;

        p2 = p;

    }

    return p1;

}

 

//在链表指定位置插入节点

Node* insert_list(Node* head, int n, Node* newNode) {

    if(n == 0) {

       newNode->next = head;

        head =newNode;

        returnhead;

    }

    Node* p =head;

    --n;

    while(n--&& p) {

        p =p->next;

    }

    if(p ==NULL) {

        returnNULL;

    }

    Node* temp =p->next;

    p->next =newNode;

   newNode->next = temp;

    return head;

}

 

//链表合并

Node * Merge(Node *head1 , Node *head2)

{

if(head1 == NULL)

return head2;

if (head2 == NULL)

return head1;

Node *head = NULL;

Node *p1 = NULL;

Node *p2 = NULL;

if (head1->data <head2->data)

{

head = head1;

p1 = head1->next;

p2 = head2;

} else {

head = head2;

p1 = head2->next;

p2 = head1;

}

Node *pcurrent = head;

while(p1!=NULL &&p2!=NULL)

{

if(p1->data <=p2->data)

{

pcurrent->next = p1;

pcurrent = p1;

p1 = p1->next;

} else {

pcurrent->next = p2;

pcurrent = p2;

p2 = p2->next;

}

}

if(p1 != NULL)

pcurrent->next = p1;

if(p2 != NULL)

pcurrent->next = p2;

return head;

}

 

 

//递归合并有序链表

Node * MergeRecursive(Node *head1 , Node *head2)

{

if (head1 == NULL)

return head2;

if (head2 == NULL)

return head1;

Node *head = NULL;

if(head1->data <head2->data)

{

head = head1;

head->next =MergeRecursive(head1->next,head2);

} else {

head = head2;

head->next =MergeRecursive(head1,head2->next);

}

return head;

}

 

 

//判断链表是否有环

struct node { char val; node* next;}

 

bool check(const node* head) {} //return false: 无环;true: 有环

 

//一种On)的办法就是(搞两个指针,一个每次递增一步,一个每次递增两步,如果有环的话两者必然重合,反之亦然):

bool check(const node* head)

{

if(head==NULL)

return false;

node *low=head

node *fast=head->next;

while(fast!=NULL&& fast->next!=NULL)

{

low=low->next;

fast=fast->next->next;

if(low==fast)

return true;

}

return false;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值