循环链表的创建
void create(int x)
{
node* newnode = new node;
newnode->v = x;
head = tail = newnode;
newnode->next = head;
num++;
}
增加
void add(int x)
{
if (num == 0)
{
printf("链表为空\n");
return;
}
else
{
node* newnode = new node;
newnode->v = x;
newnode->next = head;
tail->next = newnode;
tail = newnode;
}
num += 1;
}
插入
void Insert(int index,int x)
{
if (num == 0)
{
node* newnode = new node;
newnode->v = x;
head = tail = newnode;
}
else
{
if (index<1 || index>num)
{
printf("越界\n");
return;
}
else
{
node* search = head;
int j = 1;
for (j = 1; j < index - 1; j++)
{
search = search->next;
if (search == head)
{
break;
}
}
if (j<index-1)
{
printf("越界\n");
return;
}
node* newnode = new node;
node* t = search->next;
newnode->v = x;
newnode->next = t;
search->next = newnode;
}
}
num++;
}
删除
void Delete(int index)
{
if (index<1 || index>num)
{
printf("越界\n");
return;
}
else
{
if (index == 1)
{
node* t = head;
head = head->next;
tail->next = head;
delete t;
}
else
{
node* search = head;
for (int j = 1; j < index - 1; j++)
{
search = search->next;
if (search == head)
{
break;
}
}
if (search == head)
{
printf("越界\n");
return;
}
node* t = search->next;
search->next = t->next;
delete t;
}
}
num--;
}
完整代码
#include<iostream>
using namespace std;
struct node
{
int v;
struct node* next;
};
node* head, * tail;
int num = 0;
void create(int x)
{
node* newnode = new node;
newnode->v = x;
head = tail = newnode;
newnode->next = head;
num++;
}
void show(void)
{
node* search = head;
for (int i = 0; i < num; i++)
{
printf("%d ", search->v);
search = search->next;
}
printf("\n");
}
void Insert(int index,int x)
{
if (num == 0)
{
node* newnode = new node;
newnode->v = x;
head = tail = newnode;
}
else
{
if (index<1 || index>num)
{
printf("越界\n");
return;
}
else
{
node* search = head;
int j = 1;
for (j = 1; j < index - 1; j++)
{
search = search->next;
if (search == head)
{
break;
}
}
if (j<index-1)
{
printf("越界\n");
return;
}
node* newnode = new node;
node* t = search->next;
newnode->v = x;
newnode->next = t;
search->next = newnode;
}
}
num++;
}
void Delete(int index)
{
if (index<1 || index>num)
{
printf("越界\n");
return;
}
else
{
if (index == 1)
{
node* t = head;
head = head->next;
tail->next = head;
delete t;
}
else
{
node* search = head;
for (int j = 1; j < index - 1; j++)
{
search = search->next;
if (search == head)
{
break;
}
}
if (search == head)
{
printf("越界\n");
return;
}
node* t = search->next;
search->next = t->next;
delete t;
}
}
num--;
}
void add(int x)
{
if (num == 0)
{
printf("链表为空\n");
return;
}
else
{
node* newnode = new node;
newnode->v = x;
newnode->next = head;
tail->next = newnode;
tail = newnode;
}
num += 1;
}
int main(void)
{
create(5);
add(6);
add(7);
show();
Insert(2, 8);
show();
Delete(3);
show();
return 0;
}