双链表练习--交换节点
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;// }
相关文章推荐
- 交换链表中相邻节点的位置
- leetcode24,交换链表相邻的节点
- 交换链表相邻节点
- 两两交换链表中的节点
- LintCode入门练习——466. 链表节点计数
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- 交换链表中两个节点
- 交换链表当中两个节点
- 两两交换链表中的节点
- 【Weiss】【第03章】练习3.3:通过交换指针交换单/双链表元素
- lintcode——两两交换链表中的节点
- LintCode 两两交换链表中的节点
- LintCode入门练习——466. 链表节点计数
- 链表的冒泡排序(节点交换法)
- 双链表--节点前后插入练习
- 练习 删除链表中的重复节点、剩余节点逆序输出
- 两两交换链表中的节点
- 交换链表中的相邻节点
- 两两交换链表中的节点
- Swap Nodes in Pairs 链表交换相邻的节点