结点定义
typedef struct node {
elemtype data;
struct node *next;
} Linklist;
一.单链表
1.链表的建立
a .头插法
Linklist * init() {
Linklist *head;
Linklist *temp;
int i = 0;
head = (Linklist *)malloc(sizeof(Linklist));
head->next = null;
for ( ; i < 10 ; i ++) {
temp = (Linklist *)malloc(sizeof(Linklist));
temp->data = i;
temp - > next = head - >next;
head - > next = temp;
}
return head;
}
b.尾插法
Linklist *init() {
Linklist *head;
Linklist *p;
Linkist *temp;
int i;
head = (Linklist *)malloc(sizeof(Linklist));
head - > next = null;
p = head;
while(i < 10) {
temp = (Linklist *)malloc(sizeof(Linklist));
temp - >data = i;
temp - >next = NULL;
p - > next = temp;
p = temp;
i ++;
}
return head;
}
2.求单链表的长度
int length(Linklist *h)
{
Linklist *p;
int counter = 0;
p = h - >next;
while( p != NULL) {
counter ++;
p = p - > next;
}
return counter;
}
3.插入算法
void insert(Linklist *p,elemtype x) //将值为x的结点插在p之后
{
Linklist *new;
new = (Linklist *)malloc(sizeof(Linklist));
new - > data = x;
new - > next = p - >next;
p - > next = new;
}
在单链表的第i个元素之前插入一个元素
int insert(Linklist *h,int i, elemtype x)
{
Linklist *p;
Linklist *n;
int counter = 0;
p = h - > next;
while(p != NULL) {
if (++counter < i - 1) {
p = p - > next;
} else {
break;
}
}
n = (Linklist *)malloc(sizeof(Linklist));
n - >data = x;
n - next = p - >next;
p - >next = n;
return 1;
}
4.删除算法
删除链表中第i个元素
int delete(Linklist *h, int i)
{
Linklist *p;
Linklist *q;
int counter = 0;
p = h - >next;
while(p != NULL && (++counter < i - 1)) {
p = p - >next;
}
q = p - > next;
p - > next = q - > next;
free(q);
}
5.按值查找
Linklist *locate(Linklist *h, elemtype x)
{
Linklist *p;
p = h - > next;
while(p != NULL && p - >data != x) {
p = p - > next;
}
return (p != NULL)?p:NULL;
}
二、循环链表和双向链表
1.循环链表上的操作实现和单链表上基本一致,但需要在算法中的循环条件p或p - > next是否为空改为是否等于头指针。
下面以在循环链表中查找值为x的结点为例讨论如何实现算法
Linklist *get(Linklist *h, elemtype x)
{
Linklist *p;
p = h - > next;
while(p != h && p - > data != x) {
p = p - > next;
}
return (p != h)p:NULL;
}
2.双向链表
结构定义
typedef struct dulnode
{
elemtype data;
struct dulnode *next,*prior;
}dulnode;
a.插入算法
待续。。