循环链表的特点是从任意结点出发都能找到表中其他结点。
循环链表为空表时:h->next = h;
结束的条件为:p->next = h。
(图片来自百度)
//项目:循环链表
//时间:2011-9-30
#include"lklist_1.c"
int main()
{
linklist taillist;
int j = 1, count;
taillist = tailcreat();
printf("请输入所创建链表的元素个数:");
scanf("%d", &count);
printf("取单链表中第2个元素:");
printf("%c\n",get(taillist, 2));
printf("删除单链表中第3个元素:");
printf("%c\n",delete(taillist, 3));
printf("在链表中第3个元素之前插入c.\n");
insert(taillist, 3, 'c');
printf("依次输出单链表中的元素:");
for(j = 1; j < count + 1; j++)
{
printf("%c",get(taillist, j));
}
printf("\n");
return 0;
}
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define OK 0
#define ERROR -1
typedef char elemtype;
typedef struct node {
elemtype data;
struct node *next;
}Lnode, *linklist;
linklist tailcreat()
{
Lnode *h, *p, *t;
elemtype ch;
h = (linklist)malloc(sizeof(Lnode));
h->next = h;
t = h;
while((ch = getchar()) != '\n')
{
p = (linklist)malloc(sizeof(Lnode));
p->data = ch;
p->next = h; // 尾指针指向头结点
t->next = p;
t = p;
}
if(h->next != h)
return h;
else
return NULL;
}
//取元素
//读取单链表中第i个元素,1<=i<=length(h)
elemtype get(linklist h, int i)
{
int j = 1;
Lnode *p;
p = h->next;
while(p != h && j < i)//移动p,直到p为空,或者j < i
{
p = p->next;
j++;
}
if((p != NULL) && j == i)
return (p->data);
else
return ERROR;
else
return ERROR;
}
//删除元素
//删除i元素,并返回其值,1<=i<=length(h)
elemtype delete(linklist h, int i)
{
int j = 1;
elemtype e;
Lnode *p, *q;
p = h->next;
while((p->next != h)&& j < i-1)
{
p = p->next;
j++;
}
if((p->next != NULL) && j == i-1)
{
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return e;
}
else
return ERROR;
}
与单链表相比,顺序链表的操作没有太大的变化,只是在判断结束时有所变化。还有就是在建立的时候,需要将尾指针指向头结点。