📌  相关文章
📜  用于在链表中制作中间节点头部的Python程序

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

用于在链表中制作中间节点头部的Python程序

给定一个单链表,找到链表的中间节点,并将链表的中间节点设置在链表的开头。
例子:

Input: 1 2 3 4 5 
Output: 3 1 2 4 5

Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6 

https://media.geeksforgeeks.org/wp-content/uploads/Capturedsdw.png

这个想法是首先使用两个指针找到链表的中间,第一个一次移动一个,第二个一次移动两个。当第二个指针到达终点时,第一个到达中间。我们还跟踪第一个指针的前一个,以便我们可以将中间节点从其当前位置移除并使其成为头部。

Python3
# Python3 program to make middle node
# as head of Linked list
  
# Linked List node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
  
# function to get the middle node
# set it as the beginning of the 
# linked list
def setMiddleHead(head):
    if(head == None):
        return None
  
    # To traverse nodes 
    # one by one
    one_node = head
  
    # To traverse nodes by 
    # skipping one
    two_node = head
  
    # To keep track of previous middle
    prev = None
  
    while(two_node != None and
          two_node.next != None):
  
        # For previous node of middle node
        prev = one_node
  
        # Move one node each time
        one_node = one_node.next
  
        # Move two nodes each time
        two_node = two_node.next.next
  
    # Set middle node at head
    prev.next = prev.next.next
    one_node.next = head
    head = one_node
  
    # Return the modified head
    return head
  
def push(head, new_data):
  
    # Allocate new node
    new_node = Node(new_data)
  
    #Link the old list to new node
    new_node.next = head
  
    # Move the head to point the new node
    head = new_node
  
    # Return the modified head
    return head
  
# A function to print a given linked list
def printList(head):
    temp = head
    while (temp!=None):
          
        print(str(temp.data), end = " ")
        temp = temp.next
    print("")
  
# Create a list of 5 nodes
head = None
for i in range(5, 0, -1):
    head = push(head, i)
  
print(" list before: ", end = "")
printList(head)
  
head = setMiddleHead(head)
  
print(" list After: ", end = "")
printList(head)
# This code is contributed by Pranav Devarakonda


输出:

list before: 1 2 3 4 5
list After : 3 1 2 4 5 

请参考完整的文章在链表中制作中间节点头以获取更多详细信息!