#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
int n;
struct _node*next;
}node;
typedef struct _linkedlist{
node*head;
}linkedlist;
void Addtotail(linkedlist*plist, int number);
void Addtohead(linkedlist*plist, int number);
void Print(linkedlist*plist);
void Free(linkedlist*plist);
int Insertnode(linkedlist*plist,int number);
void main(){
linkedlist list;
list.head=NULL;
int n,N;
do{
scanf("%d",&n);
if(n!=-1)
Addtotail(&list,n);
}while(n!=-1);
Print(&list);
do{
scanf("%d",&N);
if(N!=-1)
if(Insertnode(&list,N)==-1)
printf("内存耗尽");
}while(N!=-1);
Print(&list);
Free(&list);
}
void Addtotail(linkedlist*plist, int number){
node*p=(node*)malloc(sizeof(node));
p->n=number;
p->next=NULL;
node*last=plist->head;
if(plist->head!=NULL){
while(last->next!=NULL)
last=last->next;
last->next=p;
}else
plist->head=p;
}
void Addtohead(linkedlist*plist, int number){
node*p=(node*)malloc(sizeof(node));
p->n=number;
p->next=NULL;
if(plist->head!=NULL){
p->next=plist->head;
node*q=p;
p=plist->head;
plist->head=q;
}else
plist->head=p;
}
void Print(linkedlist*plist){
node*p=plist->head;
while(p!=NULL){
printf("%d ",p->n);
p=p->next;
}printf("\n");
}
void Free(linkedlist*plist){
node*p=plist->head;
node*q=NULL;
while(p!=NULL){
q=p->next;
free(p);
p=q;
}
}
int Insertnode(linkedlist*plist,int number){
node*p=(node*)malloc(sizeof(node));
if(p==NULL)
return -1;
p->n=number;
p->next=NULL;
node*q=plist->head;
if(p->n<=q->n){
Addtohead(plist,number);
return 1;
}
else{
node*r=q->next;//有序,所以至少有两个node
while(p->n>r->n){
q=r;
r=r->next;
if(r==NULL){
Addtotail(plist,number);
return 1;
}
}
p->next=r;
q->next=p;
return 1;
}
}
(含链表头添法、尾添法)写一个函数 int insertNode(LinkedList* pList, int number); 实现将一个结点插入到从小到大排列的链表中。-1表示内存耗尽,1表示成功
最新推荐文章于 2022-10-02 12:06:53 发布