题意:给出一个单链表,将位于奇数位和偶数位的分组,重新组成链表,要求空间复杂度为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;
}
}