该代码为循环链表相关代码
实现如下功能:
1. 初始化带头结点和尾指针的空循环链表
2. 判断循环链表是否为空
3. 计算链表长度
4. 返回链表尾指针
5. 头插法建立单链表
6. 尾插法建立单链表
7. 两循环链表的合并
8. 循环链表的打印
#include<stdio.h>
#include<stdlib.h>
#include <windows.h>
#define FALSE 0
#define TRUE 1
typedef int DataType;
typedef struct Node
{
DataType info;
struct Node *link;
}QNode;
typedef struct Node *PNode;
typedef struct Node *LinkList;
// 初始化带头结点和尾指针的空循环链表
LinkList initList()
{
PNode rear;
LinkList head = (QNode*)malloc(sizeof(QNode));
if (head == NULL)
{
exit(0);
}
head->link = head;
rear = head;
return rear;
}
// 判断循环链表是否为空
int isNullList_link(LinkList llist)
{
return(llist->link == llist);
}
// 计算链表长度
int ListLength(LinkList llist)
{
PNode p = llist->link;
int i = 0;
while(p != llist)
{
i++;
p = p->link;
}
return i;
}
// 返回链表尾指针
PNode returnRear(LinkList llist)
{
PNode p = llist;
PNode rear = NULL;
while (p->link != llist)
{
p = p->link;
}
rear = p;
return rear;
}
// 头插法建立单链表
void createListHead(LinkList head)
{
PNode p = NULL;
int data;
head->link = head;
printf("请输入整型数据建立链表,以-1结束:\n");
scanf("%d", &data);
if (data == -1)
{
printf("该链表为空链表。\n");
}
while(data != -1)
{
p = (QNode *)malloc(sizeof(QNode));
p->info = data;
p->link = head->link;
head->link = p;
scanf("%d", &data);
}
}
// 尾插法建立单链表
void createListTail(LinkList head)
{
PNode p = NULL;
PNode rear = head;
int data;
printf("请输入整型数据建立链表,以-1结束:\n");
scanf("%d", &data);
if (data == -1)
{
printf("该链表为空链表。\n");
}
while(data != -1)
{
p = (QNode *)malloc(sizeof(QNode));
p->info = data;
p->link = head;
rear->link = p;
rear = p;
scanf("%d", &data);
}
}
// 两链表的合并
LinkList addCirLink(LinkList llist, PNode rear1, PNode rear2)
{
PNode p, q;
p = rear1->link;
rear1->link = rear2->link->link;
// 将本是指向B表的第一个结点(非头结点)赋值给rear1->link
q = rear2->link;
rear2->link = p;
// 将原表1的头结点赋值给表2的尾指针下一位
free(q);
// 释放原表2头结点
return llist;
}
// 单链表的打印
void print(LinkList llist)
{
PNode p = NULL;
p = llist->link;
if(p == NULL)
{
printf("该链表为空。\n");
exit(0);
}
while(p->info != NULL)
{
printf("%d\t", p->info);
if (p->link != llist)
p = p->link;
else
{
/*
测试是否是循环链表语句
printf("**%d**", p->link->link->info);
*/
printf("\n");
break;
}
}
}
int main()
{
LinkList lx_alist1, lx_alist2;
PNode rear1, rear2;
int num,len,i,x;
int temp;
int j,k;
lx_alist1 = initList();
lx_alist2 = initList();
printf("判断链表是否为空(1为空):%d\n", isNullList_link(lx_alist1));
printf("\n ====== 头插法创建链表: ====== \n");
createListHead(lx_alist1);
print(lx_alist1);
printf("\n ====== 尾插法创建链表: ====== \n");
createListTail(lx_alist2);
print(lx_alist2);
printf("\n ====== 返回两链表尾指针: ====== \n");
rear1 = returnRear(lx_alist1);
rear2 = returnRear(lx_alist2);
printf("已返回两链表尾指针,分为别rear1, rear2 \n");
printf("\n ====== 两链表合并: ====== \n");
addCirLink(lx_alist1, rear1, rear2);
print(lx_alist1);
system("pause");
return 0;
}