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