建立双向循环链表,实现双向循环链表的删除操作。
#include <stdio.h>
int nodeNum = 5;
struct node
{
int t;
node * llink;
node * rlink;
};
//建表
struct node *creatlist()
{
int i = 0;
int t;
struct node *head, *p, *q;
//头结点
scanf_s("%d", &t);
head = new struct node;
head->t = t;
head->llink = 0;
head->rlink = 0;
q = head;
for (i = 0; i < nodeNum - 1; i++) {
scanf_s("%d", &t);
p = new struct node;
p->t = t;
p->llink = q;
p->rlink = 0;
q->rlink = p;
q = q->rlink;
}
q->rlink = head;
head->llink = q;
return head;
}
//删除
struct node *deleteOne(struct node *head, int i)
{
if (head == 0) {
printf("这是个空表\n");
return head;
}
else if (i<0 || i>nodeNum) {
printf("指定元素不存在\n");
return head;
}
//可以删除
struct node *q;
if (i == 0) {
q = head;
head = head->rlink;
}
else if(i < nodeNum / 2){
struct node *p;
p = head;
//从左往右找
for (int j = 0; j < i - 1; j++) {
p = p->rlink;
}
q = p->rlink;
p->rlink = q->rlink;
q->rlink->llink = p;
}
else {
struct node *p;
p = head;
//从右往左找
for (int j = 0; j < nodeNum - i - 1; j++) {
p = p->llink;
}
q = p->llink;
p->llink = q->llink;
q->llink->rlink = p;
}
delete q;
nodeNum--;
return head;
}
//打印
void print(struct node *head)
{
struct node *tmp = head;
int i = 0;
while (i < nodeNum)
{
printf("%d ", tmp->t);
tmp = tmp->rlink;
i++;
}
printf("\n");
}
//释放
void removeAll(struct node *head)
{
struct node*p = head;
for (int i = 0; i < nodeNum; i++) {
p = head;
head = head->rlink;
delete p;
nodeNum = 0;
}
}
int main()
{
int i;
struct node *head = NULL;
struct node *h = NULL;
//创建链表
printf("输入5个值\n");
head = creatlist();
//删除
printf("删除第几个元素\n");
scanf_s("%d", &i);
i = i - 1;
head = deleteOne(head, i);
//head = deleteOne(h, i);//空链表
//打印单链表
printf("删除后的链表为:\n");
print(head);
//释放
removeAll(head);
return 0;
}
?
|