一、單鏈表頭文件的使用
#include <stdio.h>
#include <stdlib.h>
#define Type int
#define ERROR(str) printf("%s,%s,%s,%d",str,__FILE__,__FUNCTIONW__,__LINE__);
#define N 10
二、單鏈表節點的構建
struct Link
{
Type data;
struct Link* next;
} ;
三、單鏈表節點的初始化
struct Link* link_init ( Type elem)
{
struct Link* temp = ( struct Link* ) malloc ( sizeof ( struct Link) ) ;
if ( temp == NULL )
{
ERROR ( "結構體爲空" ) ;
}
temp-> data = elem;
temp-> next = NULL ;
return temp;
}
四、單鏈表的創建
struct Link* link_cteate ( Type arr[ ] , int num)
{
struct Link* head= NULL ;
struct Link* end = head;
for ( int i = 0 ; i< num; i++ )
{
if ( head == NULL )
{
head = link_init ( arr[ i] ) ;
end = head;
continue ;
}
struct Link* temp = link_init ( arr[ i] ) ;
end-> next = temp;
end = temp;
}
return head;
}
五、單鏈表元素增加
void link_insert ( struct Link* head, int index, Type elem)
{
struct Link* temp = head;
if ( 1 == index)
{
struct Link* Newnode = link_init ( elem) ;
Newnode-> next = head-> next;
Newnode-> data = head-> data;
head-> data = elem;
head-> next = Newnode;
return ;
}
for ( int i = 1 ; i < index - 1 ; i++ )
{
temp = temp-> next;
}
struct Link* newnode = link_init ( elem) ;
newnode-> next = temp-> next;
temp-> next = newnode;
}
六、單鏈表元素刪除
void link_delete ( struct Link* head, int index)
{
struct Link* temp = head;
if ( 1 == index)
{
struct Link* temp = head-> next;
head-> data = head-> next-> data;
head-> next = head-> next-> next;
free ( temp) ;
return ;
}
for ( int i = 1 ; i < index - 1 ; i++ )
{
temp = temp-> next;
}
struct Link* newnode= temp-> next;
temp-> next = temp-> next-> next;
free ( newnode) ;
}
七、單鏈表元素的查找
int link_get ( struct Link* head, int elem)
{
int i;
struct Link* temp = head;
for ( i = 1 ; i <= N; i++ )
{
if ( temp-> data == elem)
break ;
temp = temp-> next;
}
return i;
}
八、單鏈表元素的輸出
void link_out ( struct Link* head)
{
struct Link* temp= head;
while ( temp != NULL )
{
printf ( "%d\t" , temp-> data) ;
temp = temp-> next;
}
printf ( "\n" ) ;
}
九、單鏈表的使用
int main ( )
{
Type arr[ N] ;
printf ( "請輸入要輸入的%d個元素\n" , N) ;
for ( int i = 0 ; i < N; i++ )
{
scanf_s ( "%d" , & arr[ i] ) ;
}
struct Link* p= link_cteate ( arr, N) ;
printf ( "要輸出的元素爲:\n" ) ;
link_out ( p) ;
link_insert ( p, 1 , 30 ) ;
printf ( "插入元素後:\n" ) ;
link_out ( p) ;
link_delete ( p, 1 ) ;
printf ( "刪除元素後:\n" ) ;
link_out ( p) ;
int a = link_get ( p, 6 ) ;
printf ( "該元素位置爲:%d\n" , a) ;
system ( "pause" ) ;
return 0 ;
}