文件: root - text - article - 2019 - 10 - reverse-a-linked-list.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 537 次阅读, 20489 次搜索 | 149 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | 英文 | 主页 | 类别: 计算机科学 | 537 次阅读, 20489 次搜索 | 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, | 英文 | 主页 | 类别: 计算机科学 | 537 次阅读, 20489 次搜索 | 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
猜您喜欢...
- Longest Substring Without Repeating Characters
- Number of Ways to Climb Stairs
- Daily Interview Problem: Room scheduling
- Algorithm Interview: No Adjacent Repeating Characters
- Two Tricks of Delphi
- Daily Interview Problem: Word Ordering in a Different Alphabetical Order
- Binary Tree Level with Minimum Sum
- Invert a Binary Tree
- Daily Interview Problem: Buddy Strings
- Multitasking
©2006~2024 牛排过熟 - 0.01136 秒 - 1737.429 KB/s - 32 在线 内存: 493.2 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)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。