这里对单链表的循环模式写了一些代码,只是单纯从原理上做出了说明,并没有加入相关的容错
单链表亦即ring buffer
单链表的循环模式和非循环的单链表有什么很大的区别,只是在初始时要把head->next = NULL 变成 head->next = head即可,另外在判断链表结束时的条件也要相应的从p->next == NULL 改成 p->next = head.
下面是代码
//
// main.c
// cicular_linked_list
//
// Created by zhong on 25.05.19.
// Copyright © 2019 zhong. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode
{
int data;
struct ListNode *next;
} node_t;
node_t *init()
{
node_t *head = malloc(sizeof(node_t));
head->data = 0;
head->next = head;
return head;
}
int insert_head(node_t *head, int data)
{
node_t *newnode = malloc(sizeof(node_t));
newnode->data = data;
newnode->next = head->next;
head->next = newnode;
return 0;
}
int insert_index(node_t *head, int data, int index)
{
node_t *newnode = malloc(sizeof(node_t));
newnode->data = data;
while(index--)
{
head = head->next;
}
newnode->next = head->next;
head->next = newnode;
return 0;
}
int delete_head(node_t *head)
{
node_t *tmp;
tmp = head->next;
head->next = head->next->next;
free(tmp);
return 0;
}
int delete_index(node_t *head, int index)
{
node_t *tmp;
while(index--)
{
head = head->next;
}
tmp = head->next;
head->next = head->next->next;
free(tmp);
return 0;
}
int change(node_t *head, int data, int index)
{
while(index--)
{
head = head->next;
}
head->next->data = data;
return 0;
}
int search(node_t *head, int data)
{
node_t *p;
int index = -1;
p = head;
while(p->next != head)
{
p = p->next;
index++;
if(data == p->data)
{
return index;
}
}
printf("no data was found\n");
return -1;
}
int destroy(node_t *head)
{
node_t *p;
p = head;
while(p->next != head)
{
delete_head(p);
p = p->next;
}
free(head);
return 0;
}
int print_list(node_t *head)
{
node_t *p;
p = head;
while(p->next != head)
{
p = p->next;
printf("%d ", p->data);
}
printf("\n");
return 0;
}
int main(int argc, const char * argv[]) {
node_t *list;
int pos;
list = init();
for(int i=0; i<10; i++)
{
insert_head(list, i);
}
print_list(list);
insert_index(list, 20, 1);
print_list(list);
delete_head(list);
print_list(list);
delete_index(list, 1);
print_list(list);
change(list, 80, 0);
print_list(list);
pos = search(list, 20);
printf("the position is %d\n", pos);
destroy(list);
return 0;
}