文件: root - text - article - 2019 - 10 - reverse-a-linked-list.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 361 次阅读, 19058 次搜索 | 149 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 361 次阅读, 19058 次搜索 | 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
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 361 次阅读, 19058 次搜索 | 149 个单词 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 Interview Question: Find Cycles in a Graph
- Daily Interview Problem: Tree Serialization
- Daily Interview Problem: Room scheduling
- Find the non-duplicate number
- First and Last Indices of an Element in a Sorted Array
- PHP Unit Tests on VPS Server
- Algorithm Interview: Convert Roman Numerals to Decimal
- Daily Interview Problem: Minimum Removals for Valid Parenthesis
- New Vulnerabilities (CVE-2016-4581) have been detected in CentOS/RHEL/CloudLinux 7
- Daily Interview Problem: Reverse Words in a String
©2006~2024 牛排过熟 - 0.01346 秒 - 4009.05 KB/s - 11 在线 内存: 520.17 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
牛排怎么做才好吃? | <meta name="机器人" content="不索引, 跟踪" />
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
评论 (0)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。