页面顶部 Top
文件:  root - text - article - 2019 - 10 - reverse-a-linked-list.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 307 次阅读, 16084 次搜索 | 149 个单词

定阅此目录的博客 | 浏览 | 博客存档
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
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 307 次阅读, 16084 次搜索 | 149 个单词 定阅此目录的博客

猜您喜欢...

  1. Linode Support Ticket 10029540 - Other - Important Notice Regarding Ubuntu 17.10 Image
  2. Algorithm Interview: No Adjacent Repeating Characters
  3. Daily Interview Problem: Room scheduling
  4. Find Missing Numbers in an Array
  5. Spreadsheet Columns
  6. Making a Height Balanced Binary Search Tree
  7. Daily Interview Problem: Deepest Node in a Binary Tree
  8. Algorithm Interview: Permutations of numbers
  9. Fibonacci coding
  10. ImageMagick Vulnerabilities -  CVE-2016–3714

评论 (0)

    当前页暂时没有评论。


最后更新: October 30 2020 14:21:12 | RSS Subscription
牛排怎么做才好吃? | <meta name="机器人" content="索引, 跟踪">