• 面试题-----单链表的反转


    #include <iostream>
    using namespace std;
    
    struct node{
        int value;
        struct node *next;
    };
    
    struct node *head;
    
    void insert(struct node * &head,int value)
    {
        if(head == NULL)
        {
            head = new struct node;
            head->value = value;
            head->next = NULL;
            return;
        }
    
        struct node *p = new struct node;
        p->value = value;
        p->next = NULL;
    
        struct node *q = head;
        while(q->next != NULL)
        {
            q = q->next;
        }
    
        q->next = p;
    
    }
    
    void print(struct node *head)
    {
        struct node *p = head;
        while(p != NULL)
        {
            cout<<p->value<<"  ";
            p = p->next;
        }
    }
    void reverse(struct node * &head)
    {
    
        if(head == NULL || head->next == NULL)
            return;
        struct node *p = head;
        struct node *q = head->next;
    
        while(q != NULL)
        {
            struct node *next = q->next;
            q->next = p;
            p = q;
            q = next;
        }
        head->next = NULL;
        head = p;
    }
    
    int main()
    {
        head = NULL;
    
        insert(head,1);
        insert(head,3);
        insert(head,5);
        insert(head,9);
        insert(head,11);
        insert(head,16);
        insert(head,18);
        insert(head,6);
        insert(head,10);
        insert(head,12);
        insert(head,13);
        insert(head,15);
        cout<<"链表:";
        print(head);
        cout<<endl<<"逆序后为:"<<endl;
        reverse(head);
        print(head);
        cout<<endl;
    
        return 0;
    }

     还可以使用递归实现

    //递归实现
    struct node *reverse2(struct node *head)
    {
        if(head == NULL || head->next == NULL)
            return head;
    
        struct node *p;
        struct node *next = head->next;
        p = reverse2(next);
        next->next = head;
        head->next = NULL;
        return p;
    }
  • 相关阅读:
    【MapReduce】三、MapReduce运行机制
    【MapReduce】二、MapReduce编程模型
    【MapReduce】一、MapReduce简介与实例
    配置集成测试环境 phpstudy
    系统安装
    项目测试的流程
    黑.白盒测试
    黑盒测试等价划分实例
    软件测试的概述
    单元测试框架unitest和自动化测试高级应用
  • 原文地址:https://www.cnblogs.com/qingergege/p/7825393.html
Copyright © 2020-2023  润新知