#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node * next;
} Node;
typedef struct Node * Linklist;
Status GetElem ( Linklist L, int i, ElemType * e)
{
int j;
Linklist p;
p= L-> next;
j= 1 ;
while ( p && j< i)
{
p= p-> next;
++ j;
}
if ( ! p || j> i)
return ERROR;
* e= p-> data;
return OK;
}
Status LinkInsert ( Linklist * L, int i, ElemType e)
{
int j;
Linklist n, p, s;
n= p= * L;
j= 1 ;
while ( p && j< i)
{
p= p-> next;
++ j;
}
if ( ! p || j> i)
return ERROR;
s = ( Linklist) malloc ( sizeof ( Node) ) ;
s-> data= e;
s-> next= p-> next;
p-> next= s;
n-> data++ ;
return OK;
}
Status ListDelete ( Linklist* L, int i, ElemType* e)
{
int j= 1 ;
Linklist p, n, q;
n= p= * L;
while ( p-> next && j< i)
{
p= p-> next;
++ j;
}
if ( ! ( p-> next) || j> i)
return ERROR;
q= p-> next;
p-> next= q-> next;
* e= q-> data;
free ( q) ;
n-> data-- ;
return OK;
}
void CreateListHead ( Linklist * L, int n)
{
Linklist p;
int i;
srand ( time ( 0 ) ) ;
* L = ( Linklist) malloc ( sizeof ( Node) ) ;
( * L) -> next= NULL ;
for ( i= 0 ; i< n; i++ )
{
p= ( Linklist) malloc ( sizeof ( Node) ) ;
p-> data = rand ( ) % 100 + 1 ;
p-> next = ( * L) -> next;
( * L) -> next = p;
( * L) -> data++ ;
}
}
void CreateListTail ( Linklist * L, int n)
{
Linklist p, r;
int i;
srand ( time ( 0 ) ) ;
* L= ( Linklist) malloc ( sizeof ( Node) ) ;
r= * L;
for ( i= 0 ; i< n; i++ )
{
p= ( Node* ) malloc ( sizeof ( Node) ) ;
p-> data= rand ( ) % 100 + 1 ;
r-> next= p;
r= p;
( * L) -> data++ ;
}
r-> next= NULL ;
}
Status ClearList ( Linklist * L)
{
Linklist p, q;
p= ( * L) -> next;
while ( p)
{
q= p-> next;
free ( p) ;
p= q;
}
( * L) -> next = NULL ;
( * L) -> data= 0 ;
return OK;
}
int main ( )
{
Linklist L, p;
printf ( "********测试CreateListTail函数测试********\n" ) ;
CreateListTail ( & L, 10 ) ;
ClearList ( & L) ;
p= L;
int length= p-> data;
printf ( "Linklist的长度=%d\n" , p-> data) ;
for ( int i= 0 ; i< length; i++ )
{
p= p-> next;
printf ( "Linklist[%d]=%d\n" , i+ 1 , p-> data) ;
}
}
单链表结构与顺序存储结构优缺点
存储分配方式:是否是连续的存储单元; 时间性能:查找,插入和删除; 空间性能:需不需要预分配存储空间;