easy
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
return
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 ...
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 ...
思路: - use double pointer, to maintain 2 list: regular & evenlist
- pointer: even, odd modify current node. evenHead(2 in this case) always point the start of evenlist
- travel the list to adjust nodes until reach end of evenlist
Complexity: Time O(N) Space O(1)
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; } }
思路2: - use double pointer, to maintain 2 list:odd& evenlist
- Traverse the list till end
- Then connect odd & even list
Complexity: Time O(N) Space O(1)
Preview (hint: you can copy and paste the preview into Microsoft Word):
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ oddStart = ListNode(0) evenStart = ListNode(0) oddN = oddStart evenN = evenStart counter = 1 while(head != None): if(counter % 2 != 0): oddN.next = head oddN = oddN.next else: evenN.next = head evenN = evenN.next head = head.next counter += 1 evenN.next = None oddN.next = evenStart.next return oddStart.next
No comments:
Post a Comment