数据结构实验之链表六:有序链表的建立(SDUT 2121)

2023-03-09 16:47:17 浏览数 (1)

代码语言:javascript复制
#include <bits/stdc  .h>

using namespace std;

struct node
{
    int data;
    struct node *next;
};
int main()
{
    int n;
    struct node *head,*tail,*p,*q,*t;
    scanf("%d",&n);
    head = new node;
    head -> next = NULL;
    tail = head;
    for(int i = 0; i < n; i   )
    {
        p = new node;
        p -> next = NULL;
        scanf("%d",&p->data);
        if(head -> next == NULL){
            tail -> next = p;
            tail = p;
        }
        else {
            int f = 1;
            q = head;
            t = q -> next;
            while(t)
            {
                if(p->data > t -> data){
                    q = q ->next;
                    t = t -> next;
                }
                else {
                    p->next =q ->next;
                    q -> next = p;
                    f = 0;
                    break;
                }
            }
            if(f) {tail -> next = p;
            tail = p;}
        }
    }
    for(p = head -> next; p != NULL; p = p -> next)
    {
        if(p==head->next)printf("%d",p->data);
        else printf(" %d", p -> data);
    }
    printf("n");
    return 0;
}

0 人点赞