Reorder List Program (Leetcode:
You are given the head of a singly linked list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4] Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5] Output: [1,5,2,4,3]
Constraints:
- The number of nodes in the list is in the range
[1, 5 * 104]
. 1 <= Node.val <= 1000
print 'hello world!'# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
if not head:
return
temp = head
mid = head
while temp != None and temp.next != None:
mid = mid.next
temp = temp.next.next
rev = self.reverseList(mid)
new = head
while rev.next != None:
temp_new = new.next
new.next = rev
temp_rev = rev.next
rev.next = temp_new
new = temp_new
rev = temp_rev
def reverseList(self, head):
p1 = None
p2 = head
while p2 != None:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
return p1
0 Comments
Please don't enter any spam link in comment box.
Emoji