单链表的正向排序,反向排序

这里实现正向排序之后利用一下单链表的逆置Reverse ()便得到反向排序结果

#include 
using namespace std;
#include 


struct Node 
{
int data;
Node *next;
};


Node *InsertSort_List(void)
{
int data=0;
Node *head=NULL;
Node *NewNode,*CurNode,*PreNode;


while(1)
{
cout<<"please input the data: ";
cin>>data;
if(data==0)
break;


NewNode=(Node *)malloc(sizeof(Node));
NewNode->data=data;
NewNode->next=NULL;


if(head==NULL)
{
head=NewNode;
continue;
}


if(NewNode->data <= head->data )
{
NewNode->next=head;
head=NewNode;//为头结点赋值
continue;
}


CurNode=head;
PreNode=head;
while(NewNode->data > CurNode->data && CurNode->next!=NULL)
{
PreNode=CurNode;
CurNode=CurNode->next;
}


if(NewNode->data <= CurNode->data)
{
PreNode->next=NewNode;
NewNode->next=CurNode;
}
else
CurNode->next=NewNode;
}
return head;
}


void print(Node *head)
{
Node *p;
int i=1;
p=head;
while(p!=NULL)
{

cout<<"The "<data<next;
i++;
}
cout<next==NULL)
return head;


q=p->next;
p->next=NULL;


while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
head=p;
return head;
}


int main()
{
Node *head,*Rever;


head=InsertSort_List();
print(head);
Rever=reverse(head);
print(Rever);


return 0;
}

运行结果如下:

单链表的正向排序,反向排序_第1张图片


你可能感兴趣的:(C/C++)