定义数据
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
/* 定义节点 */
typedef struct Node {
ElemType val;
struct Node *next;
} Node, *PNode;
/* 定义链表 */
typedef struct LinkList {
PNode head;
int length;
} LinkList, *PLinkList;
创建链表
/* 将数组转为链表 */
LinkList transfor(ElemType *array, int size) {
PLinkList plist = (PLinkList) malloc(sizeof(LinkList));
plist->head = (PNode) malloc(sizeof(Node));
plist->length = 0;
PNode p = plist->head;
PNode q = NULL;
int i;
for(i = 0; i < size; i++) {
q = (PNode) malloc(sizeof(Node));
q->val = array[i];
p->next = q;
p = q;
plist->length++;
}
p->next = NULL;
return *plist;
}
打印链表
void printAll(LinkList list) {
PNode p = list.head;
int i;
printf("{");
for(i = 0; i < list.length; i++) {
p = p->next;
printf(" %d", p->val);
}
printf(" }\n");
}
头插法添加节点
/* 在头部添加节点 */
void addHead(PLinkList plist, ElemType e) {
PNode head = plist->head;
PNode p = (PNode) malloc(sizeof(Node));
p->val = e;
p->next = head->next;
head->next = p;
plist->length++;
}
尾插法添加节点
/* 在尾部添加节点 */
void addTail(PLinkList plist, ElemType e) {
PNode p = plist->head;
PNode q = (PNode) malloc(sizeof(Node));
q->val = e;
while(p->next) {
p = p->next;
}
p->next = q;
q->next = NULL;
plist->length++;
}
在指定位置插入节点
Status insert(PLinkList plist, int i, ElemType e) {
if(i < 1 || i > plist->length + 1) {
printf("插入位置越界\n");
return ERROR;
}
PNode p = plist->head;
int j = 1;
while(j < i) {
p = p->next;
j++;
}
PNode q = (PNode) malloc(sizeof(Node));
q->val = e;
q->next = p->next;
p->next = q;
plist->length++;
return OK;
}
删除节点
Status del(PLinkList plist, int i, ElemType *e) {
if(i < 1 || i > plist->length) {
printf("删除位置越界\n");
return ERROR;
}
PNode p = plist->head;
int j = 1;
while(j < i) {
p = p->next;
j++;
}
PNode q = p->next;
*e = q->val;
p->next = q->next;
free(q);
plist->length--;
return OK;
}
定位元素位置
/* 定位元素在表中的位置 */
int locateElem(LinkList list, ElemType e) {
PNode p = list.head->next;
int i = 1;
while(p) {
if(p->val == e) {
return i;
}
p = p->next;
i++;
}
return -1;
}
判断元素是否在表中
Status inList(LinkList list, ElemType e) {
return locateElem(list, e) != -1 ? TRUE : FALSE;
}
清空链表
void clearList(PLinkList plist) {
if(!plist) {
return;
}
PNode p = plist->head->next;
PNode q = NULL;
if(p) {
q = p->next;
free(p);
p = q;
}
plist->length = 0;
}