zoukankan      html  css  js  c++  java
  • 面试题-----单链表的反转

    #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;
    }
  • 相关阅读:
    SqlHelper使用详解
    c# 分布式事务以及MSDTC
    DataGridView隔行显示不同的颜色
    C# WinForm开发系列 DataGridView
    使用SQLHelper类调用带输出、返回参数的存储过程
    MySQLHelper类使用说明
    搜索页面———心得
    侨光卡路网站的工作点滴记录
    服务地图功能的开发心得
    成功项目经理手册
  • 原文地址:https://www.cnblogs.com/qingergege/p/7825393.html
Copyright © 2011-2022 走看看