/*10.2-7-2011-05-08-19.40.c -- 第十章第二节第七题*/
#include
#include
/*明显常量定义*/
#define FALSE (0)
#define TRUE (1)
/*数据类型定义*/
typedef int BOOL ;
typedef int Item ;
typedef struct node
{
Item item ;
struct node * next ;
} Node ;
typedef Node * LinkedList ;
/*接口函数声明*/
void Initialize_L (LinkedList * const pl) ;
BOOL IsEmpty_L (const LinkedList * const pl) ;
BOOL Insert_L (LinkedList * const pl, const Item item) ;
void Traversal_L (const LinkedList * const pl, void (* pfun) (const Item item)) ;
void Release_L (LinkedList * const pl) ;
/*接口函数定义*/
void Initialize_L (LinkedList * const pl)
{
*pl = NULL ;
}
BOOL IsEmpty_L (const LinkedList * const pl)
{
if (NULL == *pl)
return TRUE ;
else
return FALSE ;
}
BOOL Insert_L (LinkedList * const pl, const Item item)
{
Node * newNode ;
newNode = (Node *) malloc (sizeof (Node)) ;
if (NULL == newNode)
return FALSE ;
newNode -> item = item ;
if (IsEmpty_L (pl))
{
newNode -> next = NULL ;
*pl = newNode ;
}
else
{
newNode -> next = *pl ;
*pl = newNode ;
}
return TRUE ;
}
void Traversal_L (const LinkedList * const pl, void (* pfun) (const Item item))
{
Node * scan ;
for (scan = *pl; scan != NULL; scan = scan -> next)
(* pfun) (scan -> item) ;
}
void Release_L (LinkedList * const pl)
{
Node * scan, * temp ;
scan = *pl ;
while (scan != NULL)
{
temp = scan ;
scan = scan -> next ;
free (temp) ;
}
*pl = NULL ;
}
/*主例程*/
int mian (void) ;
void printItem (const Item item) ;
void reverse (LinkedList * const pl) ;
int main (void)
{
LinkedList list ;
Item item ;
Initialize_L (&list) ;
item = 1 ;
Insert_L (&list, item) ;
item = 2 ;
Insert_L (&list, item) ;
item = 3 ;
Insert_L (&list, item) ;
item = 4 ;
Insert_L (&list, item) ;
item = 5 ;
Insert_L (&list, item) ;
Traversal_L (&list, printItem) ;
reverse (&list) ;
Traversal_L (&list, printItem) ;
Release_L (&list) ;
return 0 ;
}
void printItem (const Item item)
{
printf ("%-3d/n", item) ;
}
void reverse (LinkedList * const pl)
{
Node * current, * next, * temp ;
/*If linkedlist is empty or only has one node.*/
if (IsEmpty_L (pl) || NULL == (*pl) -> next)
return ;
current = *pl ;
next = current -> next ;
while (next -> next != NULL)
{
temp = next -> next ;
next -> next = current ;
current = next ;
next = temp ;
}
next -> next = current ;
(*pl) -> next = NULL ;
*pl = next ;
}