📌  相关文章
📜  用于以交替的奇数和偶数节点顺序排列单链表的Python程序

📅  最后修改于: 2022-05-13 01:56:56.608000             🧑  作者: Mango

用于以交替的奇数和偶数节点顺序排列单链表的Python程序

给定一个单链表,重新排列列表,使偶数和奇数节点在列表中交替出现。
这种重排有两种可能的形式。如果第一个数据是奇数,那么第二个节点必须是偶数。第三个节点必须是奇数,依此类推。请注意,第一个节点是偶数、第二个奇数、第三个偶数等的另一种排列也是可能的。
例子:

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

方法1(简单):
在这种方法中,我们创建了两个堆栈——奇数和偶数。我们遍历列表,当我们在奇数位置遇到偶数节点时,我们将该节点的地址推入偶数堆栈。如果我们在偶数位置遇到一个奇数节点,我们将该节点的地址推送到奇数堆栈。
遍历列表后,我们只需弹出两个堆栈顶部的节点并交换它们的数据。我们不断重复此步骤,直到堆栈变空。

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
# Python program to rearrange nodes
# as alternate odd even nodes in
# a Singly Linked List
  
# Link list node 
class Node:     
    def __init__(self, data): 
        self.data = data 
        self.next = next
          
# A utility function to print
# linked list
def printList( node):
    while (node != None) :
        print(node.data , 
              end = " ")
        node = node.next
      
    print("")
  
# Function to create newNode
# in a linkedlist
def newNode(key):
    temp = Node(0)
    temp.data = key
    temp.next = None
    return temp
  
# Function to insert at beginning
def insertBeg(head, val):
    temp = newNode(val)
    temp.next = head
    head = temp
    return head
  
# Function to rearrange the
# odd and even nodes
def rearrangeOddEven(head):
    odd = []
    even = []
    i = 1
  
    while (head != None): 
        if (head.data % 2 != 0 and 
            i % 2 == 0):
  
            # Odd Value in Even Position
            # Add pointer to current node
            # in odd stack
            odd.append(head)
          
        elif (head.data % 2 == 0 and 
              i % 2 != 0): 
  
            # Even Value in Odd Position
            # Add pointer to current node
            # in even stack
            even.append(head)
  
        head = head.next
        i = i + 1
  
    while (len(odd) != 0 and 
           len(even) != 0) :
  
        # Swap Data at the top of two stacks
        odd[-1].data, even[-1].data = even[-1].data, odd[-1].data
        odd.pop()
        even.pop()
      
    return head
  
# Driver code
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)
# This code is contributed by Arnab Kundu


Python
# Python3 program to rearrange nodes 
# as alternate odd even nodes in 
# a Singly Linked List 
  
# Structure node 
class Node :
    def __init__(self):
        self.data = 0
        self.next = None
  
# A utility function to print 
# linked list 
def printList(node) :
    while (node != None) :
        print(node.data, 
              end = " ") 
        node = node.next
      
    print(" ")
  
# Function to create newNode 
# in a linkedlist 
def newNode(key) :
    temp = Node() 
    temp.data = key 
    temp.next = None
    return temp 
  
# Function to insert at beginning 
def insertBeg(head, val) :
    temp = newNode(val) 
    temp.next = head 
    head = temp 
    return head 
  
# Function to rearrange the 
# odd and even nodes 
def rearrange(head) :
  
    # Step 1: Segregate even and odd nodes 
    # Step 2: Split odd and even lists 
    # Step 3: Merge even list into odd list 
    even = None
    temp = None
    prev_temp = None
    i = None
    j = None
    k = None
    l = None
    ptr = None
  
    # Step 1: Segregate Odd and Even Nodes 
    temp = (head).next
    prev_temp = head 
  
    while (temp != None) :
      
        # Backup next pointer of temp 
        x = temp.next
  
        # If temp is odd move the node 
        # to beginning of list 
        if (temp.data % 2 != 0) :        
            prev_temp.next = x 
            temp.next = (head) 
            (head) = temp 
          
        else:        
            prev_temp = temp 
          
        # Advance Temp Pointer 
        temp = x 
      
    # Step 2 
    # Split the List into Odd and even 
    temp = (head).next
    prev_temp = (head) 
  
    while (temp != None and 
           temp.data % 2 != 0) :
        prev_temp = temp 
        temp = temp.next
      
    even = temp 
  
    # End the odd List (Make last 
    # node None) 
    prev_temp.next = None
  
    # Step 3: 
    # Merge Even List into odd 
    i = head 
    j = even 
  
    while (j != None and 
           i != None):
      
        # While both lists are not 
        # exhausted Backup next 
        # pointers of i and j 
        k = i.next
        l = j.next
  
        i.next = j 
        j.next = k 
  
        # ptr points to the latest 
        # node added 
        ptr = j 
  
        # Advance i and j pointers 
        i = k 
        j = l 
  
    if (i == None):
      
        # Odd list exhausts before even, 
        # append remainder of even list to odd. 
        ptr.next = j 
          
    # The case where even list exhausts 
    # before odd list is automatically 
    # handled since we merge the even 
    # list into the odd list 
    return head
  
# Driver Code 
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) 
# This code is contributed by Arnab Kundu


输出:

Linked List:
1 2 3 5 6 7 8 
Linked List after Rearranging:
1 2 3 6 5 8 7

时间复杂度: O(n)
辅助空间: O(n)

方法2(高效):

  1. 分离列表中的奇数和偶数值。在此之后,所有奇数将一起出现,然后是所有偶数。
  2. 将列表拆分为奇数和偶数两个列表。
  3. 将偶数列表合并为奇数列表
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

# Python3 program to rearrange nodes 
# as alternate odd even nodes in 
# a Singly Linked List 
  
# Structure node 
class Node :
    def __init__(self):
        self.data = 0
        self.next = None
  
# A utility function to print 
# linked list 
def printList(node) :
    while (node != None) :
        print(node.data, 
              end = " ") 
        node = node.next
      
    print(" ")
  
# Function to create newNode 
# in a linkedlist 
def newNode(key) :
    temp = Node() 
    temp.data = key 
    temp.next = None
    return temp 
  
# Function to insert at beginning 
def insertBeg(head, val) :
    temp = newNode(val) 
    temp.next = head 
    head = temp 
    return head 
  
# Function to rearrange the 
# odd and even nodes 
def rearrange(head) :
  
    # Step 1: Segregate even and odd nodes 
    # Step 2: Split odd and even lists 
    # Step 3: Merge even list into odd list 
    even = None
    temp = None
    prev_temp = None
    i = None
    j = None
    k = None
    l = None
    ptr = None
  
    # Step 1: Segregate Odd and Even Nodes 
    temp = (head).next
    prev_temp = head 
  
    while (temp != None) :
      
        # Backup next pointer of temp 
        x = temp.next
  
        # If temp is odd move the node 
        # to beginning of list 
        if (temp.data % 2 != 0) :        
            prev_temp.next = x 
            temp.next = (head) 
            (head) = temp 
          
        else:        
            prev_temp = temp 
          
        # Advance Temp Pointer 
        temp = x 
      
    # Step 2 
    # Split the List into Odd and even 
    temp = (head).next
    prev_temp = (head) 
  
    while (temp != None and 
           temp.data % 2 != 0) :
        prev_temp = temp 
        temp = temp.next
      
    even = temp 
  
    # End the odd List (Make last 
    # node None) 
    prev_temp.next = None
  
    # Step 3: 
    # Merge Even List into odd 
    i = head 
    j = even 
  
    while (j != None and 
           i != None):
      
        # While both lists are not 
        # exhausted Backup next 
        # pointers of i and j 
        k = i.next
        l = j.next
  
        i.next = j 
        j.next = k 
  
        # ptr points to the latest 
        # node added 
        ptr = j 
  
        # Advance i and j pointers 
        i = k 
        j = l 
  
    if (i == None):
      
        # Odd list exhausts before even, 
        # append remainder of even list to odd. 
        ptr.next = j 
          
    # The case where even list exhausts 
    # before odd list is automatically 
    # handled since we merge the even 
    # list into the odd list 
    return head
  
# Driver Code 
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) 
# This code is contributed by Arnab Kundu

输出:

Linked List:
10 2 1 5 3 6 7 8 
Rearranged List
7 10 3 2 5 6 1 8

时间复杂度: O(n)
辅助空间: O(1)

有关详细信息,请参阅有关单链表中交替奇数和偶数节点的完整文章!