• 表逆置[数组和链表]


    对于数组(也可为线性表),逆置就是首尾数据两两交换,首先计算交换的次数:

    交换次数=(len-1)/2

    #include <iostream>
    using namespace std;
    int main()
    {    
        int a[]={1,2,3,4,5,7,8,9};
        int len=sizeof(a)/sizeof(int);/*计算数组长度*/
        int temp;/*临时变量*/
        for(int i=0;i<=(len-1)/2;i++)/*计算交换次数*/
        {
            temp=a[i];
            a[i]=a[len-1-i];/*交换*/
            a[len-1-i]=temp;
        }
        for(i=0;i<len;i++)/*查看结果*/    
        cout<<a[i]<<" ";
        return 0;
    }

    第二种,链表,这个困难很多,因为链表只有一个头指针,要依赖这个指针对整个链条进行操作,需要很高的技巧!首先观察链表:

    如果逆置(反序),交换数据是不可能的,只有换种思路,把结点之间的指针指向反转,按照这种思路,头变尾,尾变头,而最困难的是如何改变指针方向?这里采用了步步转换的方法,除头指针L外,还借助两个游标指针q和r辅助移动!

    代码

    void ReverseList(List &L) /*逆序操作*/
    {
        List q,p,r;
        p=L;
        q=p->next;
        p->next=NULL;/*把头结点变成尾结点*/
        while(q!=NULL)/*游标q、r配合L进行操作*/
        {                
            r=q->next;
            q->next=L;
            L=q;
            q=r;    
        }
    
    }


    只看代码可能并不难,但是这种转移很巧妙,要背住可能需要多次演练!大概的形式是:


    L,q,r三者的先后关系看清楚,更容易记忆,L在后,q居中,r总在最前,这是在程序运行过程中产生的顺序,仅仅是一种记忆方式!

    完整代码

    #include <iostream>
    using namespace std;
    typedef struct node
    {
        int data;
        struct node *next;
    }*List,Node;
    void CreatList(List &L)
    {
        int e;
        cin>>e;
        if(e==0) /*输入0时链表创建结束*/
        L=NULL;
        else
        {
            L=(List)malloc(sizeof(Node));
            L->data=e;
            CreatList(L->next);
        }
    }
    void TraverseList(List &L) /*遍历,打印链表*/
    {
        while(L)
        {
            cout<<L->data<<" ";
            L=L->next;
        };
    }
    void ReverseList(List &L) /*逆序操作*/
    {
        List q,p,r;
        p=L;
        q=p->next;
        p->next=NULL;/*把头结点变成尾结点*/
        while(q!=NULL)/*游标q、r配合L进行操作*/
        {                
            r=q->next;
            q->next=L;
            L=q;
            q=r;    
        }
    
    }
    void DestoryList(List &L)/*销毁*/
    {
        if(L)
        {
            List(L->next);
            free(L);
            L=NULL;
        }
    }
    int main(void)
    {
        List L;
        CreatList(L);/*创建*/
        ReverseList(L);/*逆序*/
        TraverseList(L);/*遍历*/
        DestoryList(L);/*销毁*/
        return 0;
    }
  • 相关阅读:
    【11_83】Remove Duplicates from Sorted List
    【10_169】Majority Element
    【09_242】Valid Anagram
    【08_238】Product of Array Except Self
    【07_226】Invert Binary Tree
    【6_100】Same Tree
    【5_283】Move Zeroes
    【4_237】Delete Node in a Linked List
    mysql性能优化-慢查询分析、优化索引和配置
    生成商品条形码代码事例
  • 原文地址:https://www.cnblogs.com/tinaluo/p/5252587.html
Copyright © 2020-2023  润新知