1、单链表结构体定义
2、单链表带头结点的头插法
3、单链表带头结点的尾插法
4、查找第 i 个位置的值
5、按值查找
6、节点的插入
7、节点的删除
8、单链表的打印
9、完整程序
# define _CRT_SECURE_NO_WARNINGS
# include <stdio.h>
# include <stdlib.h>
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode * next;
} LNode, * LinkList;
LinkList CreatList1 ( LinkList& P_headNode) {
P_headNode = ( LinkList) malloc ( sizeof ( LNode) ) ;
P_headNode-> next = NULL ;
LNode* s;
int x;
scanf ( "%d" , & x) ;
while ( x != 9999 ) {
s = ( LNode* ) malloc ( sizeof ( LNode) ) ;
s-> data = x;
s-> next = P_headNode-> next;
P_headNode-> next = s;
scanf ( "%d" , & x) ;
}
return P_headNode;
}
LinkList CreatList2 ( LinkList& P_headNode) {
P_headNode = ( LinkList) malloc ( sizeof ( LNode) ) ;
P_headNode-> next = NULL ;
LNode* s, * r = P_headNode;
int x;
scanf ( "%d" , & x) ;
while ( x != 9999 ) {
s = ( LNode* ) malloc ( sizeof ( LNode) ) ;
s-> data = x;
r-> next = s;
r = s;
scanf ( "%d" , & x) ;
}
r-> next = NULL ;
return P_headNode;
}
LNode* GetElement ( LinkList& L, int i) {
int j = 1 ;
LNode* p = L-> next;
if ( i == 0 )
return L;
if ( i < 1 )
return NULL ;
while ( p && j < i) {
p = p-> next;
j++ ;
}
return p;
}
LinkList LocateElem ( LinkList& L, ElemType e) {
LinkList p = L-> next;
while ( p!= NULL && p-> data != e) {
p = p-> next;
}
return p;
}
bool ListFrontInsert ( LinkList& L, int site, ElemType data) {
LinkList p = GetElement ( L, site- 1 ) ;
if ( NULL == p) {
return false;
}
LNode* n = ( LNode* ) malloc ( sizeof ( LNode) ) ;
n-> data = data;
n-> next = p-> next;
p-> next = n;
return true;
}
bool ListDelete ( LinkList& L, int site) {
LinkList p = GetElement ( L, site- 1 ) ;
if ( NULL == p) {
return false;
}
LinkList q = p-> next;
p-> next = q-> next;
free ( q) ;
q = NULL ;
return true;
}
void printLinkList2 ( LinkList L) {
L = L-> next;
while ( L != NULL ) {
printf ( "%d" , L-> data) ;
L = L-> next;
if ( L != NULL ) {
printf ( " " ) ;
}
}
printf ( "\n" ) ;
}
int main ( ) {
LinkList L;
CreatList1 ( L) ;
printLinkList2 ( L) ;
CreatList2 ( L) ;
printLinkList2 ( L) ;
LNode* n = GetElement ( L, 2 ) ;
if ( n != NULL ) {
printf ( "%d\n" , n-> data) ;
}
LNode* n2 = LocateElem ( L, 6 ) ;
if ( n2) {
printf ( "%d\n" , n2-> data) ;
}
ListFrontInsert ( L, 2 , 99 ) ;
printLinkList2 ( L) ;
ListDelete ( L, 2 ) ;
printLinkList2 ( L) ;
return 0 ;
}