Simulate linked list, use simulated linked list to implement insertion sort

Analog linked list


        The simulated linked list is different from the linked list, it does not need to use the malloc() function, so it cannot achieve dynamic definition. The data in the linked list and the address of the next node are defined as a structure. In the analog linked list, two arrays are used to store these two parts. The same subscript in the two arrays can be regarded as a whole, and one array stores the data. , and the other stores the address (subscript) of the next node.


Insertion Sort Using Simulated Linked List


#include <stdio.h>

int main(void)
{
    int date[100],right[100]; //date[] stores data, right[] stores the next node subscript
    int head,i,n,t; //head is used to store the subscript of the first node of the linked list

    head=1; //Initialize head to a
    right[head]=0; //At the beginning, the subscript of the next node of the first node is 0
                            //equivalent to the successor in the linked list is NULL
    scanf("%d",&n);

    for(i=1;i<=n;++i)
    {
        scanf("%d",date+i);

        if( i>1)
        {
            if(date[head]>date[i])
            {
                right[i]=head;
                head=i;
            }
            else
            {
                t=head;
                while(t!=0) //traverse the linked list to find "position"
                {
                    if(date[right[t]]>date[i] || 0==right[t])
                    {
                        right[i]=right[t ]; //Give the address of the subsequent node of the node where t is located to the subsequent node of i
                        right[t]=i; //Set the subsequent node of the node where t is located to i
                        break; //If you do not add break, it will fall into an infinite loop
                    }
                    t =right[t];
                }
            }
        }
    }

    t=head;
    while(t) //traverse the linked list and output the values ​​in the linked list
    {
        printf("%-4d",date[t]);
        t=right[t] ;
    }

    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383689&siteId=291194637