您的位置:首页 > 其它

LeetCode Odd Even Linked List

2016-06-04 10:38 204 查看
题意:给出一个单链表,将位于奇数位和偶数位的分组,重新组成链表,要求空间复杂度为O(1)

思路:用四个结点,其中两个表示奇数链表的头和尾,另外两个表示偶数链表的头和尾,注意,偶数链表的尾可能为空或者不为空,在不为空时,需要将下一结点置为空

代码如下:

class Solution
{
public ListNode oddEvenList(ListNode head)
{
if (null == head) return head;

ListNode oddhead = null;
ListNode oddtail = null;
ListNode evenhead = null;
ListNode eventail = null;

ListNode p = head;

int cnt = 1;
while (p != null)
{
if (1 == cnt % 2)
{
if (null == oddhead)
{
oddhead = p; oddtail = p;
}
else
{
oddtail.next = p;
oddtail = oddtail.next;
}
}
else
{
if (null == evenhead)
{
evenhead = p; eventail = p;
}
else
{
eventail.next = p;
eventail = eventail.next;
}
}

p = p.next;
cnt++;
}
if (eventail != null) eventail.next = null;
oddtail.next = evenhead;

return oddhead;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: