您的位置:首页 > 其它

双链表练习--交换节点

2013-07-24 00:00 274 查看
建立一个双链表,设计一个算法查找第一个元素值为5的节点,将其与后继结点进行交换。

#include <iostream.h>
#include <stdio.h>
#define M 5

typedef struct DLinkList{
int x;//data x;
struct DLinkList *next;//pointing to the next DLinkList;
struct DLinkList *prior;//pointing to the prior DLinkList;
}DLinkList;
void main(){
//set an empty link;
DLinkList *head,*pr;
head=new DLinkList;
head->next=head;
head->next=head;
pr=head;//pr points to the last node;
//seting a link with m nodes;
for(int i=1;i<=M;i++){
DLinkList *p=new DLinkList;//creat a new node;
cin>>p->x;//Do input 5 only once;
pr->next=p;//let the last node's  next point to p;
p->prior=pr;//let the newly-created node's prior point to the last node;
p->next=head;//let the newly-created node's next point to the head node;
head->prior=p;//let the head node 's prior point to the created node;
pr=p;//let pr point to the newly-created node;
}
//finding the node with x=5;
pr=head;
while(pr->x!=5){
pr=pr->next;
}
//exchanging *pr for the node after *pr;
DLinkList *ps=pr->next;//creating a point ps pointing to the one after *pr
DLinkList *pt=ps->next;//creating a point pt pointing to the one after *ps
pr->prior->next=ps;//let the node before *pr's next point to *ps;
ps->prior=pr->prior;//let *ps's prior point to the node before *pr;
ps->next=pr;//let *ps's next point to the node  *pr
pr->prior=ps;//let *pr'prior point to *ps;
pr->next=pt;//let *pr's next point to the node after *ps;
pt->prior=pr;//let the node after *ps point to *pr;
pr=head->next;//pr points to the node with data;
while(pr!=head){//one circle
cout<<pr->x<<" ";
pr=pr->next;
}
cout<<endl;//
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: