本题两种解法:
1.分别申请odd, even两个头结点。用count来区分奇数偶数。head在链表上后移进行遍历,如果为奇数,将结点添加到odd中,将odd末尾置为null,如果为偶数,将结点添加到 even中,将末尾置为null(为了避免出现环),count+1。最后将even添加到odd末尾,返回odd。此解法没有改变原链表结构,空间复杂度高。
2.在链表上直接进行操作,记录偶数结点开始的位置。然后对链表进行断开连接。
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
JAVA
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode oddEvenList(ListNode head) { ListNode odd = new ListNode(0); ListNode even = new ListNode(0); ListNode p = odd; ListNode q = even; int count = 1; while(head != null){ if(count % 2 == 1){ p.next = head; head = head.next; p = p.next; p.next = null; } else{ q.next = head; head = head.next; q = q.next; q.next = null; } count ++; } p.next = even.next; return odd.next; } }
class Solution { public ListNode oddEvenList(ListNode head) { if(head == null) return null; ListNode odd = head; ListNode even = head.next; ListNode evenhead = head.next; 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; } }
Python3
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if head == None or head.next == None: #头结点限定条件 return head odd = head even = head.next t = even #!!!记录偶数结点的起始位置 while even != None and even.next != None: #!!!遍历结点,保持奇数偶数结点的相对位置 odd.next = even.next #连接奇数结点 odd = odd.next #调整位置 even.next = odd.next #连接偶数结点 even = even.next #调整位置 odd.next = t #整合链表 return head