📌  相关文章
📜  用于在给定大小的组中反转链表的Python程序 – 设置 1

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

用于在给定大小的组中反转链表的Python程序 – 设置 1

给定一个链表,编写一个函数来反转每 k 个节点(其中 k 是函数的输入)。

例子:

算法反向(head,k)

  • 反转大小为 k 的第一个子列表。在反转时跟踪下一个节点和前一个节点。让指向下一个节点的指针为next ,指向前一个节点的指针为prev 。请参阅此帖子以反转链表。
  • head->next = reverse(next, k) (递归调用列表的其余部分并链接两个子列表)
  • 返回prevprev成为列表的新头部(参见本文的迭代方法图)

下图显示了反向函数的工作原理:

下面是上述方法的实现:

Python
# Python program to reverse a 
# linked list in group of given size
  
# Node class
class Node:
  
    # Constructor to initialize the 
    # node object
    def __init__(self, data):
        self.data = data
        self.next = None
  
  
class LinkedList:
  
    # Function to initialize head
    def __init__(self):
        self.head = None
  
    def reverse(self, head, k):      
        if head == None:
          return None
        current = head
        next = None
        prev = None
        count = 0
  
        # Reverse first k nodes of the linked list
        while(current is not None and 
              count < k):
            next = current.next
            current.next = prev
            prev = current
            current = next
            count += 1
  
        # next is now a pointer to (k+1)th node
        # recursively call for the list starting
        # from current. And make rest of the list as
        # next of first node
        if next is not None:
            head.next = self.reverse(next, k)
  
        # prev is new head of the input list
        return prev
  
    # Function to insert a new node at 
    # the beginning
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
  
    # Utility function to print the 
    # Linked List
    def printList(self):
        temp = self.head
        while(temp):
            print temp.data,
            temp = temp.next
  
# Driver code
llist = LinkedList()
llist.push(9)
llist.push(8)
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
  
print "Given linked list"
llist.printList()
llist.head = llist.reverse(llist.head, 3)
  
print "Reversed Linked list"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


输出:

Given Linked List
1 2 3 4 5 6 7 8 9 
Reversed list
3 2 1 6 5 4 9 8 7 

复杂性分析:

  • 时间复杂度: O(n)。
    列表的遍历只进行一次,它有“n”个元素。
  • 辅助空间: O(n/k)。
    对于每个大小为 n、n/k 或 (n/k)+1 的链表,将在递归期间进行调用。

请参阅完整的文章在给定大小的组中反转链接列表 |设置 1 了解更多详情!