#include"list.h"
void InitList(List *list)
{
Node *s=(Node *)malloc(sizeof(Node));
assert(s!=NULL);
list->first=list->last=s;
list->first->prev=list->last;
list->last->next=list->first;
list->size=0;
}
void push_back(List *list, ElemType x)
{
Node *s=(Node *)malloc(sizeof(Node));
assert(s!=NULL);
s->data=x;
list->last->next=s;
s->prev=list->last;
list->last=s;
list->first->prev=list->last;
list->last->next=list->first;
list->size++;
}
void push_front(List *list, ElemType x)
{
Node *s = (Node *)malloc(sizeof(Node));
assert(s != NULL);
s->data = x;
s->prev=list->first;
s->next=list->first->next;
list->first=s;
s->next->prev=s;
if(list->size==0)
list->last=s;
list->size++;
}
void pop_back(List *list)
{
if(list->size==0)
cout<<"表空,不能删除!"<<endl;
list->last=list->last->prev;
free(list->first->prev);
if(list->size==1)
list->last=list->first;
list->first->prev=list->last;
list->last->next=list->first;
list->size--;
}
void pop_front(List *list)
{
if(list->size==0)
cout<<"表空,不能删除!"<<endl;
Node *p=list->first->next;
list->first->next=p->next;
p->next->prev=list->first;
free(p);
if(list->size==1)
{
list->last=list->first;
list->last->next=list->first;
list->first->prev=list->last;
}
list->size--;
}
void show_list(List *list)
{
Node *p = list->first->next;
while(p != list->first)
{
cout<<p->data<<"-->";
p = p->next;
}
cout<<"Over!"<<endl;
}
Node* find(List *list, ElemType key)
{
Node *p=list->first->next;
while(p!=list->first&&p->data!=key)
p=p->next;
if(p!=list->first)
return p;
return NULL;
}
bool delete_val(List *list, ElemType key)
{
Node *q=find(list,key);
if(q==NULL)
return false;
if(q==list->last)
{
list->last=q->prev;
}
q->prev->next=q->next;
q->next->prev=q->prev;
free(q);
list->size--;
return true;
}
bool insert_val(List *list, ElemType x)
{
Node *p = find(list,x);
if(p != NULL)
return false;
Node *s = (Node *)malloc(sizeof(Node));
assert(s != NULL);
s->data = x;
p = list->first;
while(p->next != list->first)
{
if(x<p->next->data)
break;//如果x小于第一个,则跳出循环执行下面操作
p = p->next;
}
s->next = p->next;
p->next->prev = s;
s->prev = p;
p->next = s;
if(p == list->last)//如果x大于最后一个,将list->last指向s即可
{
list->last = s;
}
list->size++;
return true;
}
bool resver(List *list)//从第二个节点开始按照顺序头插
{
Node *p = list->first->next;
Node *q = p->next;
p->next = list->first;
list->first->prev = p;
list->last = p;
while(p!=list->first)
{
p = q;
q = q->next;
p->next = list->first->next;
p->next->prev = p;
p->prev = list->first;
list->first->next = p;
}
return true;
}
双向循环链表 函数的实现
最新推荐文章于 2020-07-24 20:33:42 发布