单链表:
#include <stdbool.h>
#include <stdio.h>
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode, *LinkList;
//单链表的初始化
bool InitList (LinkList L) { //带头结点的单链表
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
return true;
}
bool InitList (LinkList L) { //不带头结点的单链表
L = NULL;
return true;
}
//以下默认带头结点
//求表长
int Length(LinkList L) {
int len = 0;
LNode *p = L;
while (p->next != NULL) {
p = p->next;
len++;
}
return len;
}
//按序号查找结点
LNode *GetElem(LinkList L, int i) {
LNode *p = L;
int j = 0;
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
//按值查找结点
LNode *LocateElem(LinkList L, ElemType e) {
LNode *p = L->next;
while (p != NULL && p->data != e)
p = p->next;
return p;
}
//插入结点(不带头结点首结点需要做特殊处理:将头指针L指向新的首结点)
bool ListInsert(LinkList L, int i, ElemType e) {
LNode *p = L;
int j = 0;
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;
}
/*扩展:对某一结点进行前插操作
s->next = p->next;
p->next = s;
temp = p->data;
p->data = s->data;
s->data = temp;
*/
//删除结点(不带头结点首结点需要做特殊处理:将头指针L指向新的首结点)
bool ListDelete(LinkList L, int i, ElemType e) {
LNode *p = L;
int j = 0;
while (p != NULL && j < i-1) {
p = p->next;
j++;
}
if (p == NULL || p->next == NULL)
return false;
LNode *q = p->next;
e = q->data;
p->next = q->next;
free(q);
return true;
}
/*扩展:删除结点*p
q = p->next;
p->data = p->next->data;
p->next = q->next;
free(q);
*/
//头插法建立单链表
LinkList List_HeadInsert(LinkList L) {
LNode *s;
int x;
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
//尾插法建立单链表
LinkList List_TailInsert(LinkList L) {
int x;
L = (LNode*)malloc(sizeof(LNode));
LNode *s, *r = L;
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 L;
}
双链表:
typedef int ElemType;
typedef struct DNode {
ElemType data;
struct DNode *prior, *next;
}DNode, *DLinkList;
/*双链表插入
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
*/
/*双链表删除
p->next = q->next;
q->next->prior = p;
free(q);
*/
静态链表:
typedef int ElemType;
#define MaxSize 50
typedef struct {
ElemType data;
int next;
}SLinkList[MaxSize];