链表-结点间交换

来源:互联网 发布:ec6108v9 安装软件 编辑:程序博客网 时间:2024/06/06 00:29
//节点交换 定向排序 
//环形链表  双向链表  
//中间 首位 前面两个节点间的交换 
#include<iostream>
using namespace std;

struct node
{
int data;
node*pr;
node*next;
 } ;
 
 node*Creatnode(int d)
 {
  node*p;
  p=new node;
  p->data=d;
  p->pr=p->next=NULL;
  return p;
 }
 
void Display1(node* head)
{
node*p=head;
while(p)
{
cout<<p->data<<",";
p=p->next;
}
cout<<"\n";
}


void Display2(node* tail)
{
node*p=tail;
while(p)
{
cout<<p->data<<",";
p=p->pr;
}
cout<<"\n";
}
 
 void sort(node* head)
 {
  node*q,*p=head;
  while(p)
  {
  q=p->next;
  if(p==NULL)
  {
  cout<<"NULL list"<<endl;
}
while(q)
{
if(p->data>q->data)
{
int n=p->data;
p->data=q->data;
q->data=n;
}
q=q->next;
}
 
  p=p->next;
 }
 }
 void SwapHead(node*head)
 {
   node*p;
   p=head;
   if(p==NULL)
   {
    cout<<"NULL List"<<endl;
   }
    if(p==head)
    {
    int n=p->data;
    p->data=p->next->data;
    p->next->data=n;
    }
 }
 void SwapTail(node*tail)
 {
  node*p=tail;
  if(p==NULL)
  {
  cout<<"NULL List"<<endl;
}
if(p==tail)
{
int n=p->data;
p->data=p->pr->data;
p->pr->data=n;
}
 }
 void SwapInside(node* head)
 {
  node*p=head;
  while(p)
  {
  if(p->data==9)
  {
  int n=p->data;
  p->data=p->pr->data;
  p->pr->data=n;
}
  p=p->next;
}
 }
 void SwapHT(node*head,node*tail)
 {
  int n=head->data;
  head->data=tail->data;
tail->data=n; 
 }
 

 int main(void)
 {
 
  node*head,*tail,*p,*q;
  head=tail=Creatnode(0);
  int i,a[6]={1,9,2,6,7,3};
  for(i=0;i<6;i++)
  {
  p=Creatnode(a[i]);
  p->next=head;
  head->pr=p;
  head=p;
}
 
//正向输出 
cout<<"follw direction output"<<endl;
  Display1(head);
 
  //反向输出 
  cout<<"opposite direction output"<<endl;
  Display2(tail);
 
  //cout<<"the sorted arry"<<endl;      //整体排序 
  //sort(head);
  //Display1(head);
 
  //前两位交换 
  cout<<"swap between the prior two"<<endl;
  SwapHead(head);
  Display1(head);
 
  //末尾两位交换 
  cout<<"swap between the Last two"<<endl;
  SwapTail(tail);
  Display1(head);
 
  // 其中两位交换 
  cout<<"swap between the inside two"<<endl;
  SwapInside(head);
  Display1(head);
 
  //首位交换 
  cout<<"swap between Head and Tail"<<endl; 
  SwapHT(head,tail);
  Display1(head);
  return 0;
 }
1 0
原创粉丝点击