#include <iostream>
using namespace std;
typedef struct Node
{
int val;
struct Node* next;
}*pNode,Node;
pNode insert(pNode head, int value)
{
if(head == NULL)
{
return NULL;
}
pNode h = head;
pNode n = head->next;
pNode pv = (pNode)malloc(sizeof(Node));
if(pv == NULL)
{
cout<<"insert() malloc fail"<<endl;
return head;
}
else
{
pv->val = value;
pv->next = NULL;
}
while((h!=NULL) && (n!=NULL))
{
if(h->val > value)
{
pv->next = h;
return pv;
}
if((h->val <= value) && (n->val >= value))
{
pv->next = n;
h->next = pv;
return head;
}
h = h->next;
n = n->next;
}
if(n == NULL)
{
h->next = pv;
}
return head;
}
pNode creatLink()
{
pNode head,tail,q;
int x;
head=tail=NULL;
scanf("%d",&x);
while(x!=0)
{
q=(pNode)malloc(sizeof(Node));
q->val=x;
if(head==NULL)
head=tail=q;
else
{
tail->next=q;
tail=q;
}
scanf("%d",&x);
}
if(tail!=NULL)tail->next=NULL;
return head;
}
void display(pNode head)
{
pNode p = head;
while(p!=NULL)
{
cout<<p->val<<endl;
p = p->next;
}
}
int main()
{
pNode head = NULL;
head = creatLink();
cout<<"before insert"<<endl;
display(head);
int value = 0;
scanf("%d",&value);
cout<<"insert:"<<value<<endl;
head = insert(head,value);
cout<<"after insert"<<endl;
display(head);
}
插入一个单链表
最新推荐文章于 2024-08-22 21:24:01 发布