LoginSignup
0
0

More than 3 years have passed since last update.

アルゴリズム 体操24 Reverse a LinkedList

Posted at

Reverse a LinkedList

単一LinkedListの先頭を指定すると、LinkedListを逆順にします。反転したLinkedListの新しいヘッドを返す関数を記述します。

Screen Shot 2020-08-07 at 21.27.40.png

Solution

三つのポインターである、previous, current, next を利用して、一回のイテレーションでLinkedListを逆にすることができます。

実装

from __future__ import print_function


class Node:
  def __init__(self, value, next=None):
    self.value = value
    self.next = next

  def print_list(self):
    temp = self
    while temp is not None:
      print(temp.value, end=" ")
      temp = temp.next
    print()


def reverse(head):
  previous, current, next = None, head, None
  while current is not None:
    next = current.next  # temporarily store the next node
    current.next = previous  # reverse the current node
    previous = current  # before we move to the next node, point previous to the current node
    current = next  # move on the next node
  return previous


def main():
  head = Node(2)
  head.next = Node(4)
  head.next.next = Node(6)
  head.next.next.next = Node(8)
  head.next.next.next.next = Node(10)

  print("Nodes of original LinkedList are: ", end='')
  head.print_list()
  result = reverse(head)
  print("Nodes of reversed LinkedList are: ", end='')
  result.print_list()


main()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0