循环链表
循环链表在单链表的基础上做了一些修改,序列中最后一个节点的指针域指向序列的第一个节点,构成一个闭环。这允许在循环遍历的过程中回到节点的第一个节点。原先单链表的最后一个节点的指针域为空,在循环链表中不存在空指针域。
循环链表中的任意一个节点都可以作为起点,可以使用这个节点遍历整个序列。
节点定义
struct Node{
int data;
struct Node *next;
} *head=NULL;
链表的一些常用运算
链表中一些常用运算包括添加、删除、更新
插入节点到链表末尾
创建新的节点,遍历到序列的末尾,插入新节点
插入过程
void insertAtEnd(int value){
struct Node *newNode;
newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=value;
if (head==NULL){
head=newNode;
newNode->next=head;
}else{
struct Node *temp=head;
while(temp->next!=head){
temp=temp->next;
}
temp->next=newNode;
newNode->next=head;
}
printf("节点插入成功");
}
插入节点到链表头部
新的节点通过遍历插入到序列的头部
插入过程
void insertAtBeginning(int value){
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head = newNode;
newNode -> next = head;
}
else
{
struct Node *temp = head;
while(temp -> next != head)
temp = temp -> next;
newNode -> next = head;
head = newNode;
temp -> next = head;
}
printf("\n 节点插入成功");
}
插入节点到序列的任意位置
通过遍历序列的形式的将新的节点插入到序列的指定位置
插入过程
void insertAfter(int value, int location)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head = newNode;
newNode -> next = head;
}
else
{
struct Node *temp = head;
while(temp -> data != location)
{
if(temp -> next == head)
{
printf("未发现指定节点");
}
else
{
temp = temp -> next;
}
}
newNode -> next = temp -> next;
temp -> next = newNode;
printf("\n插入节点成功");
}
}
从序列尾部删除节点
通过遍历序列的形式,从序列中移除指定节点
移除过程
void deleteEnd()
{
if(head == NULL)
printf("链表为空");
else
{
struct Node *temp1 = head, *temp2;
if(temp1 -> next == head)
{
head = NULL;
free(temp1);
}
else{
while(temp1 -> next != head){
temp2 = temp1;
temp1 = temp1 -> next;
}
temp2 -> next = head;
free(temp1);
}
printf("\n删除节点成功");
}
}
从序列头部删除指定节点
删除过程
void deleteBeginning()
{
if(head == NULL)
printf("序列未空");
else
{
struct Node *temp = head, *last = NULL;
if(temp -> next == head)
{
head = NULL;
free(temp);
}
else{
while(temp -> next != head)
temp = temp -> next;
last = temp;
temp = head;
head = head -> next;
free(temp);
last -> next = head;
}
printf("\n删除成功");
}
}
从序列中删除指定元素
通过遍历序列,从序列中找到目标元素,删除
删除过程
void deleteSpecific(int delValue)
{
if(head == NULL)
printf("List is Empty");
else
{
struct Node *temp1 = head, *temp2;
while(temp1 -> data != delValue)
{
if(temp1 -> next == head)
{
printf("\n未在链表中发现指定元素");
}
else
{
temp2 = temp1;
temp1 = temp1 -> next;
}
}
if(temp1 -> next == head){
head = NULL;
free(temp1);
}
else{
if(temp1 == head)
{
temp2 = head;
while(temp2 -> next != head)
temp2 = temp2 -> next;
head = head -> next;
temp2 -> next = head;
free(temp1);
}
else
{
if(temp1 -> next == head)
{
temp2 -> next = head;
}
else
{
temp2 -> next = temp1 -> next;
}
free(temp1);
}
}
printf("\n删除成功");
}
}
更多内容,欢迎关注: