链表的基本操作
写给自己平时复习和使用的,后面会写的更加详细一点
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
struct link * AppendNode ( struct link * head) ;
void DisplayNode ( struct link * head) ;
struct link * DeleteNode ( struct link * head, int nodedata) ;
struct link * InsertNode ( struct link * head, int nodedata) ;
void DeleteMemory ( struct link * head) ;
struct link
{
int data;
struct link * next;
} ;
int main ( )
{
int i= 0 ;
char c= 0 ;
struct link * head= NULL ;
scanf ( " %c" , & c) ;
while ( c== 'y' || c== 'Y' )
{
printf ( "&&&\n" ) ;
head= AppendNode ( head) ;
DisplayNode ( head) ;
printf ( "Do you want to continue ?\n" ) ;
scanf ( " %c" , & c) ;
i++ ;
}
printf ( "%d Node have been appended \n" , i) ;
head= DeleteNode ( head, 3 ) ;
DisplayNode ( head) ;
head= InsertNode ( head, 3 ) ;
DisplayNode ( head) ;
DeleteMemory ( head) ;
}
struct link * AppendNode ( struct link * head)
{
struct link * p= NULL , * pr = head;
int data;
p= ( struct link * ) malloc ( sizeof ( struct link ) ) ;
if ( p== NULL )
{
printf ( "ERROR!\n" ) ;
exit ( 0 ) ;
}
if ( head== NULL )
{
head= p;
}
else
{
while ( pr-> next!= NULL )
{
pr= pr-> next;
}
pr-> next= p;
}
printf ( "please input you data \n" ) ;
scanf ( "%d" , & data) ;
p-> data= data;
p-> next= NULL ;
return head;
}
void DisplayNode ( struct link * head)
{
struct link * p= head;
int j= 1 ;
while ( p!= NULL )
{
printf ( "%5d%10d\n" , j, p-> data) ;
p= p-> next;
j++ ;
}
}
void DeleteMemory ( struct link * head)
{
struct link * p= head, * pr= NULL ;
while ( p!= NULL )
{
pr= p;
p= p-> next;
free ( pr) ;
}
}
struct link * DeleteNode ( struct link * head, int nodedata)
{
struct link * p= head, * pr= head;
if ( head== NULL )
{
printf ( "Linked Table is empty !\n" ) ;
return head;
}
while ( nodedata!= p-> data && p-> next != NULL )
{
pr= p;
p= p-> next;
}
if ( nodedata== p-> data)
{
if ( p== head)
{
head= p-> next;
}
else
{
pr-> next= p-> next;
}
free ( p) ;
}
else
printf ( "the node has not been found\n" ) ;
return head;
}
struct link * InsertNode ( struct link * head, int nodedata)
{
struct link * pr= head, * p= head, * temp= NULL ;
p= ( struct link * ) malloc ( sizeof ( struct link ) ) ;
if ( p== NULL )
{
printf ( "ERROR\n" ) ;
exit ( 0 ) ;
}
p-> next= NULL ;
p-> data= nodedata;
if ( head== NULL )
{
head= p;
}
else
{
while ( pr-> data< nodedata&& pr-> next!= NULL )
{
temp= pr;
pr= pr-> next;
}
if ( pr-> data>= nodedata)
{
if ( pr== head)
{
p-> next= head;
head= p;
}
else
{
pr= temp;
p-> next= pr-> next;
pr-> next= p;
}
}
else
{
pr-> next= p;
}
}
return head;
}