Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 
The first node is considered odd, the second node even and so on ...

Solution 1):

 /**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode OddEvenList(ListNode head) {
if(head==null)
{
return head;
}
ListNode odd = head;
ListNode even = head.next;
while(even!=null&&even.next!=null)
{
ListNode oddNext = odd.next;
ListNode evenNext = even.next;
even.next = evenNext.next;
odd.next = evenNext;
evenNext.next = oddNext;
odd = odd.next;
even = even.next; }
return head;
}
}

 Solution 2):

 1->2->3->4->5->6->7    to odd: 1->3->5  and even 2->4->6;

then return odd ->even;

 public class Solution {
public ListNode OddEvenList(ListNode head) {
if(head==null)
{
return head;
}
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while(even!=null&&even.next!=null)
{
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}

    

最新文章

  1. centos mysql开启远程访问
  2. Android 在Service中弹出对话框
  3. 谈谈用ASP.NET开发的大型网站有哪些架构方式(成本)
  4. DIV实现纵向滚动条overflow-y
  5. jQuery选择器介绍:基本选择器、层次选择器、过滤选择器、表单选择器
  6. python时间-time模块
  7. 关于Struts2的Validator的配置找不到DTD
  8. HDU-2262 Where is the canteen 概率DP,高斯消元
  9. HDU P4578 Transformation
  10. asp.net 后台对话框,确认跳转
  11. SurfaceView绘图机制
  12. 恶补web之一:html学习(2)
  13. dotnet core使用IO合并技巧轻松实现千万级消息推送
  14. js中escape对应的C#解码函数 UrlDecode
  15. c语言笔记3运算符与表达式
  16. ansible-role写法
  17. 安卓,网页控件,显示网页 Android, web controls, display web pages
  18. Scala学习笔记(六):本地函数、头等函数、占位符和部分应用函数
  19. 吴裕雄 python神经网络(8)
  20. Hibernate+maven+eclipse 实现自动建表

热门文章

  1. Sublime中开发Ruby
  2. 从零开始学C++之IO流类库(二):文件流(fstream, ifstream, ofstream)的打开关闭、流状态
  3. java--九九乘法表
  4. SQLsever2008 远程连接错误 linq
  5. [置顶] 让我爱恨的ThinkPHP Relation
  6. hadoop部署错误
  7. 350 - Pseudo-Random Numbers
  8. Android开发之简单的电子相册实现
  9. 【使用教程】论Windows下必备的抓包工具Fiddler2如何安装证书(查看Https)
  10. asp.net core + mysql + ef core + linux