1、链表的结构体
typedef struct LNode
{
ElemType data;
struct LNode * next;
} LNode, * LinkList;
2、创建链表(尾插法)
LinkList CrateList ( LinkList & L)
{
L = new LNode;
L-> next = NULL ;
LNode * r, * p;
r = L;
int x;
int m = 1 ;
printf ( "请输入整数,-1为结束\n" ) ;
while ( m)
{
printf ( "输入:" ) ;
scanf ( "%d" , & x) ;
if ( x != - 1 )
{
p = new LNode;
p-> data = x;
p-> next = NULL ;
r-> next = p;
r = p;
}
else
{
m = 0 ;
}
}
}
3、输出链表
void show ( LinkList & L)
{
LNode * p = L-> next;
printf ( "\n链表为:" ) ;
while ( p != NULL )
{
printf ( "%d " , p-> data) ;
p = p-> next;
}
printf ( "\n" ) ;
4、求表长
void Length ( LinkList L)
{
LNode * p;
int i = 0 ;
p = L-> next;
while ( p)
{
i++ ;
p = p-> next;
}
printf ( "表长为:%d" , i) ;
}
5、按序号查找
void GetElem ( LinkList L, int i)
{
LNode * p = L-> next;
int j = 1 ;
ElemType e;
while ( p && i > j)
{
p = p-> next;
j++ ;
}
if ( ! p || j > i)
{
printf ( "\n查找的序号不存在" ) ;
return ;
}
e = p-> data;
printf ( "\n查找第%d元素为:%d" , i, e) ;
}
6、按值查找
void LocElem ( LinkList L, ElemType e)
{
LNode * p = L-> next;
int j = 1 ;
while ( p && p-> data != e)
{
p = p-> next;
j++ ;
}
if ( p)
{
printf ( "\n查找%d值为第%d的元素" , e, j) ;
}
else
{
return ;
}
7、插入节点
void ListLnsert ( LinkList & L, int i, ElemType e)
{
LNode * s, * p = L;
int j = 0 ;
while ( p && j < i - 1 )
{
p = p-> next;
j++ ;
}
if ( ! p || j > i - 1 )
{
printf ( "\n无法插入" ) ;
return ;
}
s = new LNode;
s-> data = e;
s-> next = p-> next;
p-> next = s;
printf ( "\n插入成功" ) ;
}
8、删除节点
void ListDelete ( LinkList & L, int i)
{
LNode * q, * p = L;
int j = 0 ;
ElemType e;
while ( p-> next && j < i - 1 )
{
p = p-> next;
j++ ;
}
if ( ! ( p-> next) || j > i - 1 )
{
printf ( "\n无法删除" ) ;
}
q = p-> next;
p-> next = q-> next;
e = q-> data;
delete q;
printf ( "\n%d删除成功" , e) ;
}