//*********************************** |
//功能:删除单链表的第偶数个元素 |
//日期:2017年10月10日 |
//作者:Ryan2019 |
//*********************************** |
#include <iostream> |
using namespace std; |
typedef int LElemType; |
typedef struct LNode |
{ |
LElemType data; |
LNode *next; |
}* LList; |
void ListCreate(LList &L, int n,LElemType a[]); //创建链表 |
void Listshow(LList &L); //显示链表 |
void DeleteEven(LList &L); //删除单链表的第偶数个元素 |
int main() |
{ |
LList A,B,C; int m=5,n=8; |
LElemType a[5]={1,2,3,4,5}; |
LElemType b[8]={1,2,3,4,5,6,7,8}; |
ListCreate(A,m,a); |
ListCreate(B,n,b); |
ListCreate(C,0,a); |
cout<< "原链表A为:" ;Listshow(A); |
DeleteEven(A); |
cout<< "删除第偶数个元素链表为:" ; Listshow(A); |
cout<< "原链表B为:" ; Listshow(B); |
DeleteEven(B); |
cout<< "删除第偶数个元素链表为:" ; Listshow(B); |
cout<< "原链表C为:" ; Listshow(C); |
DeleteEven(C); |
cout<< "删除第偶数个元素链表为:" ; Listshow(C); |
return 0; |
} |
void ListCreate(LList &L, int n,LElemType a[]) |
{ |
LList p; int i; |
L= new LNode; L->next=NULL; |
for (i=n-1;i>=0;i--) |
{ |
p= new LNode; |
p->data=a[i]; |
p->next=L->next; |
L->next=p; |
} |
} |
void Listshow(LList &L) |
{ |
LList p; |
for (p=L->next;p;p=p->next) |
{ |
cout<<p->data<< " " ; |
} |
cout<<endl; |
} |
void DeleteEven(LList &L) |
{ |
if (!L || !L->next || !L->next->next) |
{ |
return ; |
} |
LList p,q,r; |
p=L->next; |
q=p->next; |
while (p->next && q->next) |
{ |
p->next=q->next; |
p=p->next; |
r=q; |
q=p->next; |
delete r; |
} |
if (p->next && !q->next) |
{ |
p->next=NULL; |
} |
} |