Python Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Last Updated :
18 Jan, 2022
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.
There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even and so on.
Examples:
Input: 11 -> 20 -> 40 -> 55 -> 77 -> 80 -> NULL
Output: 11 -> 20 -> 55 -> 40 -> 77 -> 80 -> NULL
20, 40, 80 occur in even positions and 11, 55, 77
occur in odd positions.
Input: 10 -> 1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8 -> NULL
Output: 1 -> 10 -> 3 -> 2 -> 5 -> 6 -> 7 -> 8 -> NULL
1, 3, 5, 7 occur in odd positions and 10, 2, 6, 8 occur
at even positions in the list
Method 1 (Simple):
In this method, we create two stacks-Odd and Even. We traverse the list and when we encounter an even node in an odd position we push this node’s address onto Even Stack. If we encounter an odd node in an even position we push this node’s address onto Odd Stack.
After traversing the list, we simply pop the nodes at the top of the two stacks and exchange their data. We keep repeating this step until the stacks become empty.
Step 1: Create two stacks Odd and Even.
These stacks will store the pointers to the nodes in the list
Step 2: Traverse list from start to end, using the variable current.
Repeat following steps 3-4.
Step 3: If the current node is even and it occurs at an odd position,
push this node's address to stack Even.
Step 4: If the current node is odd and it occurs at an even position,
push this node's address to stack Odd.
[END OF TRAVERSAL].
Step 5: The size of both the stacks will be the same. While both the
stacks are not empty exchange the nodes at the top of the two
stacks and pop both nodes from their respective stacks.
Step 6: The List is now rearranged. STOP
Python
class Node:
def __init__( self , data):
self .data = data
self . next = next
def printList( node):
while (node ! = None ) :
print (node.data ,
end = " " )
node = node. next
print ("")
def newNode(key):
temp = Node( 0 )
temp.data = key
temp. next = None
return temp
def insertBeg(head, val):
temp = newNode(val)
temp. next = head
head = temp
return head
def rearrangeOddEven(head):
odd = []
even = []
i = 1
while (head ! = None ):
if (head.data % 2 ! = 0 and
i % 2 = = 0 ):
odd.append(head)
elif (head.data % 2 = = 0 and
i % 2 ! = 0 ):
even.append(head)
head = head. next
i = i + 1
while ( len (odd) ! = 0 and
len (even) ! = 0 ) :
odd[ - 1 ].data, even[ - 1 ].data = even[ - 1 ].data, odd[ - 1 ].data
odd.pop()
even.pop()
return head
head = newNode( 8 )
head = insertBeg(head, 7 )
head = insertBeg(head, 6 )
head = insertBeg(head, 5 )
head = insertBeg(head, 3 )
head = insertBeg(head, 2 )
head = insertBeg(head, 1 )
print ( "Linked List:" )
printList(head)
rearrangeOddEven(head)
print ( "Linked List after " , "Rearranging:" )
printList(head)
|
Output:
Linked List:
1 2 3 5 6 7 8
Linked List after Rearranging:
1 2 3 6 5 8 7
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 2 (Efficient):
- Segregate odd and even values in the list. After this, all odd values will occur together followed by all even values.
- Split the list into two lists odd and even.
- Merge the even list into odd list
REARRANGE (HEAD)
Step 1: Traverse the list using NODE TEMP.
If TEMP is odd
Add TEMP to the beginning of the List
[END OF IF]
[END OF TRAVERSAL]
Step 2: Set TEMP to 2nd element of LIST.
Step 3: Set PREV_TEMP to 1st element of List
Step 4: Traverse using node TEMP as long as an even
node is not encountered.
PREV_TEMP = TEMP, TEMP = TEMP->NEXT
[END OF TRAVERSAL]
Step 5: Set EVEN to TEMP. Set PREV_TEMP->NEXT to NULL
Step 6: I = HEAD, J = EVEN
Step 7: Repeat while I != NULL and J != NULL
Store next nodes of I and J in K and L
K = I->NEXT, L = J->NEXT
I->NEXT = J, J->NEXT = K, PTR = J
I = K and J = L
[END OF LOOP]
Step 8: if I == NULL
PTR->NEXT = J
[END of IF]
Step 8: Return HEAD.
Step 9: End
Python
class Node :
def __init__( self ):
self .data = 0
self . next = None
def printList(node) :
while (node ! = None ) :
print (node.data,
end = " " )
node = node. next
print ( " " )
def newNode(key) :
temp = Node()
temp.data = key
temp. next = None
return temp
def insertBeg(head, val) :
temp = newNode(val)
temp. next = head
head = temp
return head
def rearrange(head) :
even = None
temp = None
prev_temp = None
i = None
j = None
k = None
l = None
ptr = None
temp = (head). next
prev_temp = head
while (temp ! = None ) :
x = temp. next
if (temp.data % 2 ! = 0 ) :
prev_temp. next = x
temp. next = (head)
(head) = temp
else :
prev_temp = temp
temp = x
temp = (head). next
prev_temp = (head)
while (temp ! = None and
temp.data % 2 ! = 0 ) :
prev_temp = temp
temp = temp. next
even = temp
prev_temp. next = None
i = head
j = even
while (j ! = None and
i ! = None ):
k = i. next
l = j. next
i. next = j
j. next = k
ptr = j
i = k
j = l
if (i = = None ):
ptr. next = j
return head
head = newNode( 8 )
head = insertBeg(head, 7 )
head = insertBeg(head, 6 )
head = insertBeg(head, 3 )
head = insertBeg(head, 5 )
head = insertBeg(head, 1 )
head = insertBeg(head, 2 )
head = insertBeg(head, 10 )
print ( "Linked List:" )
printList(head)
print ( "Rearranged List" )
head = rearrange(head)
printList(head)
|
Output:
Linked List:
10 2 1 5 3 6 7 8
Rearranged List
7 10 3 2 5 6 1 8
Time Complexity : O(n)
Auxiliary Space : O(1)
Please refer complete article on Alternate Odd and Even Nodes in a Singly Linked List for more details!
Similar Reads
Python Program For Sorting A Linked List That Is Sorted Alternating Ascending And Descending Orders
Given a Linked List. The Linked List is in alternating ascending and descending orders. Sort the list efficiently. Example: Input List: 10 -> 40 -> 53 -> 30 -> 67 -> 12 -> 89 -> NULL Output List: 10 -> 12 -> 30 -> 40 -> 53 -> 67 -> 89 -> NULL Input List: 1 -> 4 -> 3 -> 2 -> 5 -> NULL Output List:
4 min read
Python Program For Reversing Alternate K Nodes In A Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6-
6 min read
Python Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4 Output: 1->3->2->4 Input: 10->22->30->43->56->70 Output: 10->30->56->22->43->70Recommended: Please solv
6 min read
Python Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function sh
4 min read
Python Program For Alternating Split Of A Given Singly Linked List- Set 1
Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists 'a' and 'b'. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and
3 min read
Python Program For Finding The Middle Element Of A Given Linked List
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc
5 min read
Python Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
4 min read
Python Program For Pairwise Swapping Elements Of A Given Linked List
Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp
2 min read
Python Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15-
5 min read