?
?
??一、单链表
???(1)用代码定义单链表
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
LNode *L;
LinkList L;
?
???(2)创建单链表
LinkList L;
bool InitList(LinkList &L)
{
L = Null;
return true;
}
InitList(L);
LinkList L;
bool InitList(LinkList &L)
{
L = (LNode *)malloc(sizeof(LNode));
if (L == NULL)
{
return false;
}
L->next = NULL;
return true;
}
InitList(L);
?
???(3)单链表的插入
bool ListInsert(LinkList &L, int i, int e)
{
if (i < 1)
{
return false;
}
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
{
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool ListInsert(LinkList &L, int i, int e)
{
if (i < 1)
{
return false;
}
if (i == 1)
{
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = L;
L = s;
return true;
}
LNode *p;
int j = 1;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
{
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool InsertNextNode(LinkList *p, int e)
{
if (p == NULL)
{
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
if (s == NULL)
{
return false;
}
s->data = e;
s->next = p->next;
p = s;
return true;
}
bool InsertPriorNode(LinkList *p, int e)
{
if (p == NULL)
{
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
if (s == NULL)
{
return false;
}
s->next = p->next;
p->next = s;
s->data = p->data;
p->data = e;
return true;
}
?
???(4)单链表的删除
bool ListDelete(LinkList &L, int i, int &e)
{
if (i < 1)
{
return false;
}
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
if (p == NULL)
{
return false;
}
if (p->next == NULL)
{
return false;
}
LNode *q = p->next;
e = q -> data;
p->next = q->next;
free(q);
return true;
}
bool DeleteNode(LNode *p)
{
if (p == NULL)
{
return false;
}
LNode *q = p->next;
p->data = p->next->data;
p->next = q->next;
free(q);
return true;
}
?
???(5)单链表的查找及长度计算
LNode *FindElem(LinkList L, int e)
{
LNode *p = L->next;
while (p != NULL && p->data != e)
{
p = p->next;
}
return p;
}
int GetLength(LinkList L)
{
LNode *p = ;
int len = 0;
while (p != NULL)
{
p = p->next;
++len;
}
return len;
}
?
???(6)“尾插法” 建立单链表
LinkList List_TailInsert(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
LNode *s;
LNode *r = L;
int x;
scanf("%d", &x);
while (x != 9999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
?
???(7)“头插法” 建立单链表(链表逆置)
LinkList List_HeadInsert(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode *s;
int x;
scanf("%d", &x);
while (x != 9999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
|