To the Top
File:  root - text - article - 2019 - 10 - reverse-a-linked-list.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | English | Home Page | Category: Computing | 307 Views, 16394 Search Bots | 149 Words

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Google:

Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?

Example:
Input: 4 - 3 - 2 - 1 - 0 - NULL
Output: 0 - 1 - 2 - 3 - 4 - NULL


class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

# Function to print the list
def printList(self):
node = self
output = ''
while node != None:
output += str(node.val)
output += " "
node = node.next
print(output)

# Iterative Solution
def reverseIteratively(self, head):
# Implement this.

# Recursive Solution
def reverseRecursively(self, head):
# Implement this.

# Test Program
# Initialize the test list:
testHead = ListNode(4)
node1 = ListNode(3)
testHead.next = node1
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(1)
node2.next = node3
testTail = ListNode(0)
node3.next = testTail

print("Initial list: ")
testHead.printList()
# 4 3 2 1 0
testHead.reverseIteratively(testHead)
#testHead.reverseRecursively(testHead)
print("List after reversal: ")
testTail.printList()
# 0 1 2 3 4
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | English | Home Page | Cateogry: Computing | 307 Views, 16394 Search Bots | 149 Words Subscribe to Feed Burner

Related Articles

  1. Floor and Ceiling of a Binary Search Tree
  2. Daily Interview Problem: Validate Binary Search Tree
  3. Daily Interview Problem: Sort Colors
  4. Daily Interview Problem: Find the k-th Largest Element in a List
  5. Reverse a Linked List
  6. Sort a Partially Sorted List
  7. Daily Interview Problem: Full Binary Tree
  8. Daily Interview Problem: Largest BST in a Binary Tree
  9. New Vulnerabilities (CVE-2016-4581) have been detected in CentOS/RHEL/CloudLinux 7
  10. Making a Height Balanced Binary Search Tree

Comments (0)

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />