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

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

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");
}

c++编写实现,经过输入数据,排序,插入链表,打印链表,释放链表的过程,代码和运行截图如下

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef struct node
{
    int data;
    struct node *next;
}*pNode;

pNode InsertNode(vector<int> vecd)
{
    pNode pHead = NULL,pEnd = NULL,pTmp =NULL;
    for (size_t i = 0; i < vecd.size(); i++)
    {
        pTmp = new node;
        pTmp->next = NULL;
        pTmp->data = vecd[i];
        if (pHead == NULL)
        {
            pHead = pTmp;
            pEnd = pTmp;
        }
        else
        {
            pEnd->next = pTmp;
            pEnd = pTmp;
        }
    }
    pEnd->next = NULL;
    return pHead;
}

void PrintfNode(pNode p)
{
    while (p != NULL)
    {
        cout << p->data;
        p = p->next;
        if (p == NULL)
            cout << endl;
        else
            cout << " -> ";    
    }
}

void ReleaseNode(pNode p)
{
    pNode tmp;
    while (p != NULL)
    {
        tmp = p;
        p = p->next;
        delete tmp;
    }
}

int main()
{
    cout << "请输入数据,输入-1则结束输入" << endl;
    int num = 0;
    vector<int> vecdata;
    while (1)
    {
        cin >> num;
        if (num == -1)
            break;

        vecdata.push_back(num);
    }

    sort(vecdata.begin(), vecdata.end());//排序,默认升序

    pNode pnode = InsertNode(vecdata);//插入

    PrintfNode(pnode);//打印

    ReleaseNode(pnode);//释放内存

    system("pause");

    return 0;
}

img