首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求单链表的数据交换解决思路

2012-11-03 
求单链表的数据交换实现单链表内的元素交换操作,注意元素交换不是交换两个元素内的数据,而是整个元素的交

求单链表的数据交换
实现单链表内的元素交换操作,注意元素交换不是交换两个元素内的数据,而是整个元素的交换位置。

所以程序要实现链表结点的指针修改,而不是结点内的数据交换。

Input
第一行输入n表示顺序表包含的·n个数据

第二行输入n个数据,数据是小于100的正整数

第三行输入两个参数,表示要交换的两个位置,这里是执行第1次交换

第四行输入两个参数,表示要交换的两个位置,这里是执行第2次交换


Output
第一行输出创建后,顺序表内的所有数据,数据之间用空格隔开


第二行输出执行第1次交换操作后,顺序表内的所有数据,数据之间用空格隔开

第三行输出执行第2次交换操作后,顺序表内的所有数据,数据之间用空格隔开

注意加入交换位置的合法性检查,如果发现位置不合法,输出error。

Sample Input
5
11 22 33 44 55
1 4
2 6

Sample Output
11 22 33 44 55 
44 22 33 11 55 
error





[解决办法]
#include <iostream.h>
 #include <stdlib.h>
 template <class T>
 class linkNode 
 { //结点类
 public:
 T data;
 linkNode *link;
 linkNode(linkNode *ptr)
 {
 link=ptr;
 }
 linkNode()
 {
 link = NULL;
 }
 };
 template <class T>
 class list:public linkNode<T>
 {
 public:
 list();
 linkNode<T> *locate(int i);
 int lenght()const;
 void input(); 
 void output();
 void change(int a,int b);
 private:
 linkNode<T> *first,*current;
 };
 template <class T>
 void list<T>::output()
 {
 current=first->link;
 while (current->link!=NULL)
 cout<<current->data<<' ';
 }
 template <class T>
 list<T>::list()
 {
 first=current=new linkNode<T>;
 first->link=NULL;
 current=first;
 }
 template <class T>
 int list<T>::lenght()const{
 int count=0;
 linkNode<T> *chaxun;
 chaxun=new linkNode<T>;
 chaxun=first->link;
 while(chaxun !=NULL)
 {
 count++;
 }
 return count;
 };
 template<class T>
 linkNode<T> *list<T>::locate(int i){
 if (i<0)
 return NULL;
 linkNode<T> *a=first;
 int k=0;
 while (a!=NULL && k<i)
 {
 a=a->link;
 k++;
 }
 return a;
 };
 template <class T>
 void list<T>::input(){
 linkNode<T> *newNode;
 newNode = new linkNode<T>;
 if(newNode==NULL){
 cerr<<"存储分配错误"<<endl;
 exit(1);
 }
 cin>>newNode->data;
 newNode->link=current->link;
 current->link=newNode;
 };
 template <class T>
 void list<T>::change(int a,int b)
 {
 int count=lenght();
 if (a<1 || b>count || a>b)
 {
 cerr<<"交换有误";
 exit(1);
 }
 linkNode<T> *srt,*ptr,*p,*q,*qian,*hou;
 qian=locate(a-1);
 hou=locate(b-1);
 p=srt=locate(a);
 q=ptr=locate(b);
 qian->link=q;
 q->link=p->link;
 hou->link=srt;
 srt=ptr->link;
 };
 void main()
 {
 int n,a,w;
 list<int> arrary;
 cout<<"请输入N的大小";
 cin>>n;
 for (int i=0;i<n;i++)
 {
 arrary.input();
 }
 cout<<"请输入要交换的顺序位置:";


 cin>>a;
 cin>>w;
 arrary.change(a,w);
 arrary.output();
 cout<<endl;
 }

热点排行