📜  用于反转双向链表的Python程序

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

用于反转双向链表的Python程序

给定一个双向链表,任务是反转给定的双向链表。

例如,请参见下图。

(a) Original Doubly Linked List  

(b) Reversed Doubly Linked List  

这是一个反转双向链表的简单方法。我们需要做的就是交换所有节点的 prev 和 next 指针,更改 head(或 start)的 prev 并最终更改 head 指针。

Python
# Program to reverse a doubly linked list
# A node of the doubly linked list
class Node:
  
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
  
  
class DoublyLinkedList:
  
    # Constructor for empty Doubly 
    # Linked List
    def __init__(self):
        self.head = None
  
    # Function reverse a Doubly Linked List
    def reverse(self):
        temp = None
        current = self.head
  
        # Swap next and prev for all nodes 
        # of doubly linked list
        while current is not None:
            temp = current.prev
            current.prev = current.next
            current.next = temp
            current = current.prev
  
        # Before changing head, check for the
        # cases like empty list and list with 
        # only one node
        if temp is not None:
            self.head = temp.prev
  
    # Given a reference to the head of a list 
    # and an integer,inserts a new node on the 
    # front of list
    def push(self, new_data):
  
        # 1. Allocates node
        # 2. Put the data in it
        new_node = Node(new_data)
  
        # 3. Make next of new node as head 
        # and previous as None (already None)
        new_node.next = self.head
  
        # 4. change prev of head node to 
        # new_node
        if self.head is not None:
            self.head.prev = new_node
  
        # 5. move the head to point to the 
        # new node
        self.head = new_node
  
    def printList(self, node):
        while(node is not None):
            print node.data,
            node = node.next
  
# Driver code
dll = DoublyLinkedList()
dll.push(2)
dll.push(4)
dll.push(8)
dll.push(10)
  
print 
"Original Linked List"
dll.printList(dll.head)
  
# Reverse doubly linked list
dll.reverse()
  
print 
"Reversed Linked List"
dll.printList(dll.head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


Python3
"""
Function to reverse a doubly-linked list
swap next and prev pointers for all the 
nodes change prev of the head node
change head pointer
"""
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
  
class DoublyLinkedList:
    def __init__(self):
        self.head = None
  
    """
    Method to reverse a Doubly-Linked List 
    using Stacks
    """
    def reverseUsingStacks(self):
        stack = []
        temp = self.head
        while temp is not None:
            stack.append(temp.data)
            temp = temp.next
  
        # Add all the elements in the stack 
        # in a sequence to the stack
        temp = self.head
        while temp is not None:
            temp.data = stack.pop()
            temp = temp.next
              
        # Popped all the elements and the 
        # added in the linked list, 
        # in a reversed order.
  
    """
    Method to push a new item before 
    the head
    """
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
  
        if self.head is not None:
            self.head.prev = new_node
  
        self.head = new_node
  
    """
    Method to traverse the doubly-linked 
    list and print every node in the list
    """
    def printList(self, node):
        while(node is not None):
            print(node.data)
            node = node. next
  
# Driver code
dll = DoublyLinkedList()
dll.push(2)
dll.push(4)
dll.push(8)
dll.push(10)
  
print(
"original doubly-linked list")
dll.printList(dll.head)
  
# Reverse a doubly-linked list
dll.reverseUsingStacks()
  
print("Reversed doubly-linked list")
dll.printList(dll.head)


输出:

Original linked list 
10 8 4 2 
The reversed Linked List is 
2 4 8 10

方法二:

同样的问题也可以通过使用 Stacks 来完成。

脚步:

  1. 继续将节点的数据推入堆栈。 -> O(n)
  2. 不断弹出元素并更新双向链表

Python3

"""
Function to reverse a doubly-linked list
swap next and prev pointers for all the 
nodes change prev of the head node
change head pointer
"""
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
  
class DoublyLinkedList:
    def __init__(self):
        self.head = None
  
    """
    Method to reverse a Doubly-Linked List 
    using Stacks
    """
    def reverseUsingStacks(self):
        stack = []
        temp = self.head
        while temp is not None:
            stack.append(temp.data)
            temp = temp.next
  
        # Add all the elements in the stack 
        # in a sequence to the stack
        temp = self.head
        while temp is not None:
            temp.data = stack.pop()
            temp = temp.next
              
        # Popped all the elements and the 
        # added in the linked list, 
        # in a reversed order.
  
    """
    Method to push a new item before 
    the head
    """
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
  
        if self.head is not None:
            self.head.prev = new_node
  
        self.head = new_node
  
    """
    Method to traverse the doubly-linked 
    list and print every node in the list
    """
    def printList(self, node):
        while(node is not None):
            print(node.data)
            node = node. next
  
# Driver code
dll = DoublyLinkedList()
dll.push(2)
dll.push(4)
dll.push(8)
dll.push(10)
  
print(
"original doubly-linked list")
dll.printList(dll.head)
  
# Reverse a doubly-linked list
dll.reverseUsingStacks()
  
print("Reversed doubly-linked list")
dll.printList(dll.head)

输出:

Original linked list 
10 8 4 2 
The reversed Linked List is 
2 4 8 10

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

在这个方法中,我们遍历链表一次并将元素添加到堆栈中,然后再次遍历整体以更新所有元素。整体需要2n时间,也就是O(n)的时间复杂度。

有关详细信息,请参阅有关反向双向链表的完整文章!