分别采用头插法,尾插法,升序建立链表
#include<stdio.h>
#include<stdlib.h>
typedef struct _Node
{
int data;
struct _Node *next;
}Node;
typedef struct _list{
Node *head;
}List;
void add(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=NULL;
Node *last=pList->head;
if(last)
{
while(last->next)
{
last=last->next;
}
last->next=p;
}
else
pList->head=p;
}
void add2(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=pList->head;
pList->head=p;
}
void add3(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=NULL;
if(pList->head==NULL||p->data<pList->head->data)
{
p->next=pList->head;
pList->head=p;
}
else
{
Node *q=pList->head;
while(q->next&&p->data>q->next->data)
{
q=q->next;
}
if(q->next==NULL)
{
q->next=p;
}
else
{
p->next=q->next;
q->next=p;
}
}
}
void showL(List *pList)
{
Node *p;
for(p=pList->head;p;p=p->next)
{
printf("%d ",p->data);
}
}
int main()
{
List L;
L.head=NULL;
int n,temp;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&temp);
add3(&L,temp);
}
// int m;
//scanf("%d",&m);
//ldelete(&L,m);
showL(&L);
}