题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
主体思路比较简单,双指针:
奇数指针和偶数指针,两个指针每次走两步;
优化:
令奇数指针和偶数指针分别为p1和p2,则:
p2 = p1.next
所以只需要单指针即可完成遍历。
p2指针需要保留,用来完成两个链表的连接。
class Solution: def oddEvenList(self , head: ListNode) -> ListNode: # write code here if not head or not head.next or not head.next.next: return head p1, p2 = head, head.next while p1.next and p1.next.next: p1_next = p1.next p1.next = p1_next.next p1_next.next = p1_next.next.next p1 = p1.next p1.next = p2 return head1.head的长度小于3,直接返回head;
2.指定p1和p2;
3.因为while里面要用到p1.next.next.next,所以要保证
p1.next and p1.next.next都存在;
4.连接左右两个链表;
5.返回head;