1.单链表的操作:
创建,插入,排序,逆向输出,删除节点等的操作。
2.程序代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
void Creatlist(NODE **);
void output(NODE const *);
void freelist(NODE **);
NODE *getnode();
NODE *insertlist(NODE *head,int pos);
NODE *insertlist_node(NODE *head,NODE *pnew);
NODE *removenode(NODE *head,NODE *pnew);
int main()
{
NODE *head = NULL;
int m;
NODE *pnew=NULL;
Creatlist(&head);
output(head);
head = insertlist(head,5);
output(head);
pnew = getnode();
head = insertlist_node(head,pnew);
output(head);
head = removenode(head,pnew);
output(head);
freelist(&head);
}
void freelist(NODE **phead)
{
NODE *pp=NULL;
while(*phead !=NULL)
{
pp=*phead;
*phead = (*phead)->next;
free(pp);
}
}
NODE *insertlist(NODE *head,int pos)
{
NODE *pnew=getnode();
NODE *p=NULL;
int i;
if(head ==NULL)
{
head=pnew;
return head;
}
if(pos ==1)
{
p->next = head;
head=p;
return head;
}
i = pos -2;
p = head;
while(i !=0 && p->next !=NULL)
{
p = p->next;
--i;
}
pnew ->next = p->next;
p->next = pnew;
return head;
}
void output(NODE const *phead)
{
NODE *pp =NULL;
pp = (NODE *)phead;
while(pp!=NULL)
{
printf("%d\t",pp->data);
pp = pp->next;
}
printf("\n");
}
NODE *getnode()
{
NODE *pnew;
pnew =(NODE *)malloc(sizeof(NODE));
if(pnew == NULL)
{
exit(1);
}
scanf("%d",&(pnew->data));
pnew->next=NULL;
return pnew;
}
void Creatlist(NODE **phead)
{
NODE *pnew=NULL;
NODE *pend =NULL;
pnew =getnode();
while(pnew->data!=0)
{
if(*phead == NULL)
{
*phead = pnew;
pend = pnew;
}
else
{
pend->next = pnew;
pend = pnew;
// pnew->next = *phead;
// *phead = pnew;
}
pnew = getnode();
}
}
NODE *insertlist_node(NODE *head,NODE *pnew)
{//youxu de cha ru
int i;
NODE *p = head;
if(p == NULL)
{
head = pnew;
return head;
}
if((p == head) && (p->data) >= (pnew->data))
{
pnew->next = head;
head = pnew;
return head;
}
while(p->next != NULL)
{
if((p->data) < (pnew->data) && (p->next->data) >= (pnew->data))
{
break;
}
p = p->next;
}
pnew ->next = p->next;
p->next = pnew;
return head;
}
NODE *removenode(NODE *head,NODE *pnew)
{
NODE *pp=NULL;
pp =head;
if(head == pnew)
{
head =head->next;
return head;
}
while(pp->next !=NULL)
{
if(pp->next !=pnew)
{
pp= pp->next;
}
else
{
pp->next = pp->next->next;
free(pp->next);
return head;
}
if(pp->next ==NULL)
{
printf("here is error,please input other node!\n");
}
}
}
3.程序结果:
[root@localhost 20120818]# ./a.out
2 6 9 8 5 0
创建的链表为:
2 6 9 8 5
4
插入后的的链表为:
2 4 6 9 8 5
排序后的链表为:
2 4 5 6 8 9
逆向输出的链表为:
9 8 6 5 4 2
删除节点后的链表为:
9 8 6 5 2
[root@localhost 20120818]#