C++ 编程作业 函数insertList将tmp指向的一个Node结点插入一个按成员num从小到大排序单向链表中,并返回新链表

21.函数insertList将tmp指向的一个Node结点插入一个按成员num从小到大排序单向链表中,并返回新链表。完成该函数的编写。 样例输入:2 6 4 13 7 9 5 12样例输出:2 4 5 6 7 9 12 13 
#include <iostream>
using namespace std;
struct Node {
        int num;
        Node *next;
};
Node * insertList(Node *nd, Node *head)
{
/*********Program*********/
        int v=nd->num;
        if (head == NULL) 
        {
                head = nd;
                return head;
        }
        Node *p=head;
        if (v<=p->num) 
        {
                nd->next=head;
                head=nd;
        }
        else
        {
                while (p->next!=NULL) 
                {
                        if (v<=p->next->num)
                                break;
                        p=p->next;
                }
                nd->next=p->next;
                p->next=nd;
        }
        return head;
/*********  End  *********/
}
void deleteList(Node *head)
{
        Node *tmp;
        while (head)
        {
                tmp = head->next;
                delete head;
                head = tmp;
        }
}
void printList(Node *head)
{
        while(head)
        {
                cout<<head->num<<" ";
                head = head->next;
        }
        cout<<endl;
}
int main()
{
        int s[8];
        for(int i=0;i<8;i++){
                        cin>>s[i];
                } 
        Node * head = NULL;
        for(int i=0;i<8;i++)
        {
                Node *tmp = new Node;
                tmp->num = s[i];
                tmp->next = NULL;
                head = insertList(tmp, head);
        }
        printList(head);
        deleteList(head);
        return 0;
}

}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值