Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1413942
  • 博文数量: 241
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 2253
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-11 22:27
个人简介

--

文章分类

全部博文(241)

文章存档

2021年(3)

2019年(6)

2018年(1)

2017年(9)

2016年(21)

2015年(50)

2014年(125)

2013年(26)

我的朋友

分类: C/C++

2013-12-26 12:30:26

转自:http://blog.csdn.net/ojshilu/article/details/12222035
题目:已知链表L0->L1->L2->L3->.......->Ln-1->Ln-2->Ln.将该链表变为L0->Ln->L1->Ln-1->...................
分析:分析变化后的链表和给出的原链表关系,看出将链表平分为2段,将后半部分反转,之后按照顺序穿插即可。
别人的源码:

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <malloc.h>
  3. using namespace std;

  4. typedef struct node
  5. {
  6.     int val;
  7.     node* next;
  8. }node,*list;

  9. void displaylist(list s)
  10. {
  11.     while(s!=NULL)
  12.     {
  13.         cout<<s->val<<" ";
  14.         s = s->next;
  15.     }
  16.     cout<<endl;
  17. }

  18. int main()
  19. {
  20.     int a[] = {9,8,7,6,5,4,3,2,1};
  21.     //创建原始链表
  22.     list L=NULL;
  23.     for(int i=0;i<sizeof(a)/sizeof(int);i++)
  24.     {
  25.         node *p = (node*)malloc(sizeof(node));
  26.         p->val = a[i];
  27.         p->next = L;
  28.         L = p;
  29.     }
  30.     //非常重要的边界特殊情况检查
  31.     if(L==NULL)
  32.         return -1;

  33.     displaylist(L);

  34.     //寻找中间结点位置
  35.     node *fast=L,*slow=L;
  36.     while(fast->next!=NULL && fast->next->next!=NULL)
  37.     {
  38.         fast = fast->next->next;
  39.         slow = slow->next;
  40.     }
  41.     node *mid = slow->next;
  42.     slow->next = NULL; //正式将原链表一切为二

  43.     //将后半部分链表反转
  44.     list s2 = NULL;
  45.     node *tmp;
  46.     while(mid!=NULL)
  47.     {
  48.         tmp = mid->next;
  49.         mid->next = s2;
  50.         s2 = mid;
  51.         mid = tmp;
  52.     }
  53.     //displaylist(L);
  54.     //displaylist(s2);
  55.     
  56.     //交叉合并两个链表
  57.     list s1 = L;
  58.     while(s2!=NULL)
  59.     {
  60.         tmp = s2->next;
  61.         s2->next = s1->next;
  62.         s1->next = s2;    
  63.         s1 = s1->next->next;
  64.         s2 = tmp;
  65.     }
  66.     displaylist(L);
  67.     return 1;
  68. }

阅读(620) | 评论(0) | 转发(0) |
0

上一篇:位运算的妙用

下一篇:链表相关操作汇总

给主人留下些什么吧!~~