天天看点

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

//反转链表

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: 有环

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

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;

}