# 链表练习

#include
#include
#include
/***
** 这是链表的练习
***/

typedef struct student
{
int data;
struct student *next;
} node;
/** 创建队列 ***/
node * create()
{
int x = 0;

head = (node *) malloc( sizeof( node));

printf(" Put the num ,exit when puted the number 0\n");
while( 1 )
{

printf(" Put the num :  ");
scanf("%d", &x);

if( x != 0 )
{
s = (node *) malloc( sizeof( node));
s->data = x;
p->next = s;
p = s;
}else
{
p->next = NULL;
break;
}
}
}
/***
*** 打印链表,同时统计链表长度
***/

void list_print( node *list )
{
int length = 0;
node *p;
p = list;

if( p != NULL )
{
while( (p != NULL))
{
length++;
printf(" %d \n", p->data );
p = p->next;
}
}
printf(" list's length is %d \n", length );
}

/***
** 删除一个节点:
**  如果是第一个节点 ：
**  如果是中间的节点
***/
node *delete_node( node *head ,int num)
{
node *p1,*p2;
while( num != p1->data && p1->next != NULL)
{
p2 = p1;
p1 = p2->next;
}

if( num == p1->data )
{
{
free(p1);
}else
{
p2->next = p1->next;
}

}else
{
printf(" It doesn't find the num! \n");
}
}
/**  插入一个节点
** 1. 插入头 2 插入中间 3， 插入尾
***/
node *insert_node( node *head, int num )
{
node *p0, *p1, *p2;
/** 对插入节点 p0 赋值 **/
p0 = (node *)malloc( sizeof( node ));
p0->data = num;

while( p0->data > p1->data && p1->next != NULL )
{
p2=p1;
p1=p2->next;
}

if( (p0->data <= p1->data )&& (p1 == head ) )
{
p0->next = p1;
}else if( (p0->data <= p1->data )&& (p1 != head ))
{
p2->next = p0;
p0->next = p1;
}else
{
p1->next = p0;
p0->next = NULL;
}
}
/***
** 实现链表的排序,从小到大(冒泡排序)
***/
node * list_order( node *head )
{
node *p1,*p2, *p3, *p4,*p5,*pa;

int temp,temp1;
p1 = head;    /** 防止指针地址被修改 */

printf(" start order the list,list as follow before odered: \n") ;
list_print( p1 );
if( p1 == NULL  )

while( p1 != NULL  )
{
temp = p1 ->data ;
/** 查找后面有比其还小的数据
***/
pa=p1;
p2 = p1->next;
p4 = NULL;
while(  p2 != NULL)
{
temp1 = p2->data;
if ( temp1 < temp )
{
temp = temp1;
p4=p2;
}
p3 = p2;
p2 = p3->next;
}
if( p4 != NULL)
{
p4->data = p1->data;
p1->data = temp;
}
p1 = pa->next;
}
}

/**
** 实现链表的逆转
***/
{
node *p1,*p2,*p3;
p2 = p1->next;

if( p1 == NULL || p2 == NULL )
{
}

while( p2 != NULL )
{
p3 = p2 ->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
}

int main()
{
node *list ;

list = create();

list_print( list );

printf(" Put add num : ");
printf("\12");

list_print( list );

printf("Put  delete num : ");
scanf("%d", &del);
list = delete_node( list,del);
list_print( list );

list = list_order( list );

printf(" list after ordered as follow \n");

list_print( list );

list = node_reverse( list );

list_print( list );

return 0;
}

• 博文量
295
• 访问量
322788