单链表的存储结构的定义
//单链表的定义
typedef int ElemType;
typedef struct LNode{
ElemType val;
LNode *next;
}LinkNode;
单链表的初始化
//单链表的初始化
//void InitList(LinkList &L)
void InitList(LinkNode * &L){//L是一个引用
L = new LinkNode ;
//L = (LinkNode * )malloc(sizeof(LinkNode));
L->next = NULL;
cout << L->next << endl;
}
int main() {
LinkNode Exp;
LinkNode *pExp = &Exp;
cout << Exp.next << endl;
InitList(pExp);
cout << pExp->next << endl;
return 0;
}
//LinkList L;
// InitList(L);
// cout << L->next << endl;
单链表的销毁
//销毁单链表
void DestoryList(LinkList &L){
LinkList p;
while(L){
p=L;
L=L->next;
delete p;
}
}
清空链表
//清空单链表
void ClearList(LinkList &L){
LinkList p,q;
p = L->next;
while (p){
q = p->next;
delete p;
p = q;
}
L->next = NULL;
}
求单链表的表长
//求单链表表长
int ListLength(LinkList L){
LinkList p;
int i = 0;
p = L->next;
while (p){
i++;
p = p->next;
}
return i;
}
取第i个元素
//取值
void GetElem_L(LinkList L, int i, ElemType &e){
LinkList p;
p = L->next;
int j = 1;
while (p && j<i){
j++;
p = p->next;
}
if (j=i){
e = p->val;
}
}
按值查找
LinkList LocateElem_L(LinkList L, ElemType e){
LinkList p;
p = L->next;
while(p && p->val != e){
p = p->next;
}
if (p->val == e){
return p;
}
else
return NULL;
}
int LocateElem_L(LinkList L,ElemType e){
LinkList p;
int i = 0;
p = L->next;
while (p && p->val != e){
i++;
p = p->next;
}
if (p->val == e){
return i;
}
return 0;
}
插入
//插入
bool ListInsert(LinkList &L, int i , ElemType e){
LinkList p=L;
int j = 0;
while (p && j< i-1){
j++;
p = p->next;
}
if ( !p || j > i-1) {
return false;
}
LinkList s;
s = new LinkNode;
s->val = e;
s->next = p->next;
p->next = s;
return true;
}
删除第i个结点
//删除第i个结点
bool ListDelete(LinkList &L, int i, ElemType &e){
LinkList p = L,q;
int j = 0;
while (p->next && j< i-1){
j++;
p = p->next;
}
if (!(p->next) || j>i-1){
return false;
}
q = p->next;
p->next = q->next;
e = q->val;
delete q;
return true;
}
建立单链表
//头插法
void CreateList_H(LinkList &L, int n){
L = new LinkNode ;
L->next = NULL;
for (int i = n;i>0;i--){
LinkList p = new LinkNode ;
cin>>p->val;
p->next = L->next;
L->next = p;
}
}
尾插法
//尾插法
void CreateList(LinkList &L, int n){
L = new LinkNode ;
LinkList r = L;
for (int i = n;i>0;i--){
LinkList p = new LinkNode ;
p->next = NULL;
cin >> p->val;
r->next = p;
r = p;
}
}