链表这东西,很操蛋的,需要慢慢理清思路,删除还是不麻烦,你试试添加还要改两个指针
程序代码:#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof (Node)
typedef struct Node
{
int n;
struct Node* next;
}Node;
Node* creat(Node* head);
Node* find(Node* p,int key);
Node* del(Node* head,int key);
Node* insert(Node* head,int key,int s);
Node* sort(Node* head);
Node* destory(Node* p);
void print(Node* p);
int main()
{
Node* head=(Node*)malloc(LEN);
memset(head,0,LEN);
head=creat(head);
print(head);
head=sort(head);
print(head);
head->next=destory(head);
free(head);
head=NULL;
return 0;
}
Node* creat(Node* head)
{
Node* p=head;
int n=0;
while (p->next)
p=p->next;
while (scanf("%d",&n)&&n)
{
p=p->next=(Node* )malloc(LEN);
p->next=NULL;
p->n=n;
}
return head;
}
Node* find(Node* p,int key)
{
for (;(p->next)&&(p->next->n!=key);p=p->next);
return p;
}
Node* del(Node* head,int key)
{
Node* p=find(head,key);
if (p->next)
{
Node* tmp=p->next->next;
free(p->next);
p->next=tmp;
}
return head;
}
Node* insert(Node* head,int key,int s)
{
Node* p=find(head,key);
if (p->next)
{
Node* in=(Node*)malloc(LEN);
in->next=p->next;
in->n=s;
p->next=in;
}
return head;
}
Node* sort(Node* head)
{
Node* p=NULL;
Node* pt=NULL;
for (pt=p=head;p->next;pt=p=p->next)
while (pt->next)
if (pt->next->n<p->next->n)
{
Node* tmp=pt->next->next;
pt->next->next=p->next;
p->next=pt->next;
pt->next=tmp;
}
else
pt=pt->next;
return head;
}
Node* destory(Node* p)
{
Node* tmp=p->next;
while (p=tmp)
{
tmp=p->next;
free(p);
}
return p;
}
void print(Node* p)
{
for (;p=p->next;printf("%d ",p->n));
puts("");
}
[此贴子已经被作者于2017-3-15 02:40编辑过]




