C++单链表操:作交换节点
来源:优易学  2011-9-10 16:56:30   【优易学:中国教育考试门户网】   资料下载   IT书店

 

 //不得和头节点交换
  if (node1 == head)
  {
  return ;
  }
  else if (node2 == head)
  {
  return ;
  }
  //自己和自己就不必交换了
  if (node1 == node2)
  {
  return ;
  }
  tmp = head;
  while (tmp->_next != node1)
  {
  tmp = tmp->_next;
  }
  prenode1 = tmp;
  tmp = head;
  while (tmp->_next != node2)
  {
  tmp = tmp->_next;
  }
  prenode2 = tmp;
  postnode1 = node1->_next;
  postnode2 = node2->_next;
  //交换节点
  prenode1->_next = node2;
  node2->_next = postnode1;
  prenode1->_next = node1;
  node1->_next = postnode2;
  }

 void Print(LinkNode head,char* info)
  {
  using namespace std;
  cout<<info<<endl;
  while (head != NULL)
  {
  cout<<head<<": "<<head->_val<<" ";
  head = head->_next;
  }
  cout<<endl;
  }
  测试程序为:
  //main.cpp
  #include "Link.h"
  #include <iostream>
  using namespace std;
  int main(int argc,char* argv[])
  {
  LinkNode head = CreateLink(10);
  Print(head,"before exchanging....");
  ExchLinkNode (head,3,8);
  Print(head,"after exchanging....");
  return 0;
  }

 

上一页  [1] [2] [3] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训