单向链表③

编程实现:输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算:

输入一个正整数 n(0<n<=9)和一组(n个)升序的整数,建立单向链表,再输入一个整数 x,把 x 插入到这组数据中,使该组数据仍然有序。
输入:
4 (repeat=4)
5 (数据的个数n=5)
1 2 4 5 7 (5个有序整数)
3 (待插入整数x=3)
4 (数据的个数n=4)
1 2 5 7 (4个有序整数)
-10 (待插入整数x=-10)
3 (数据的个数n=3)
1 2 4 (3个有序整数)
100 (待插入整数x=100)
5 (数据的个数n=5)
1 2 4 5 7 (5个有序整数)
4 (待插入整数x=4)

输出:
size=6:1 2 3 4 5 7
size=5:-10 1 2 5 7
size=4:1 2 4 100
size=6:1 2 4 4 5 7

# include <stdio.h>
# include <stdlib.h>
typedef struct biao * list;
struct biao{
    int data;
    struct biao * next;
};
list create666(int n){
    list head = NULL,p = NULL,tail=NULL;
    for(int i=1;i<=n;i++){
        p=(list)malloc(sizeof(struct biao));  
        scanf("%d",&p->data);
        p->next=NULL;
        if(head==NULL)
        head=p;
        else
        tail->next=p;
        tail=p;
    }
    return head;
}
void add_print(list head,int n){
    list p1=NULL,p2=NULL,w=NULL,p3=NULL;
    int x;
    scanf("%d",&x);
    w=(list)malloc(sizeof(struct biao));   //容易忘的
    w->data=x;
    w->next=NULL;
    p1=head;
    if(p1->data>=w->data){				//w为头结点
        w->next=p1;
        head=w;
    }    
    p2=p1->next;
    while(p2){					
        if(p2->data>=x&&p1->data<=x){		//w在中间
            p1->next=w;						//注意顺序  把w赋给p1->next  反过来运行超时 
            w->next=p2;           			//注意顺序  p2赋给w->next  反过来错误
            break;
        }       
        p1=p1->next;
        p2=p1->next;    
        }
        if(p1->data<=x)
        p1->next=w;						//尾结点 注意顺序  w赋给p1->next  反过来错误
    p3=head;
    if(p3!=NULL){
        printf("size=%d:",n+1);
        while(p3->next!=NULL){
            printf("%d ",p3->data);
            p3=p3->next;
        }
        printf("%d\n",p3->data);
        }
}
int main (){
    int repeat;
    scanf("%d",&repeat);
    for(int i=1;i<=repeat;i++){
    int n;
    scanf("%d",&n);
    list head=create666(n);
    add_print(head,n);
    }
    return 0;
}

发布了42 篇原创文章 · 获赞 13 · 访问量 1873

猜你喜欢

转载自blog.csdn.net/KEVINzzh/article/details/105148803