sakura_xf 2022-06-13 11:25 采纳率: 20%
浏览 142

在c++怎样用链表实现将用户输入的每个数按从小到大顺序放入有序链表,并输出显示

c++将用户输入的每个数按从小到大顺序放入有序链表,并输出显示,用户输入-1表示输入结束。

  • 写回答

2条回答 默认 最新

  • 白驹_过隙 新星创作者: 算法与数据结构技术领域 2022-06-13 12:19
    关注

    img

    
     
    #include<iostream>
    using namespace std;
    #include <stdio.h>
    #include <stdlib.h>
    
    struct node{
        int n;
        struct node *pNext;
    }; 
    
    int main(){
        struct node *pHead = NULL, *pEnd = NULL, *pNode = NULL;
        int i = 1;
        printf("Please input a integer:\n");
        printf("end by inputing 0:");
        do{
            scanf("%d",&i);
            if(i != 0){
                pNode = (struct node *)malloc(sizeof(struct node));
                if(pNode != NULL){
                    pNode -> n = i;
                    pNode -> pNext = NULL;
                    if(pHead == NULL){
                        pHead = pNode;
                        pEnd = pNode;
                    }
                    else{
                        pEnd -> pNext = pNode;
                        pEnd = pNode;
                    }//end of if(pHead == NULL)
                }//end of if(pNode != NULL)
            }//end of if(i == 0)
        }while(i != -1);
        pNode = pHead;
        while(pNode != NULL){
            printf("%d\t", pNode -> n);
            pHead = pNode;
            pNode = pNode -> pNext;
            free(pHead);
        }
        printf("\n");
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 6月13日