应对面试练习题1:
**题目:**
知识点:单链表
难度:一星
描述:
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围:
0≤n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
如当输入链表{1,2,3}时,经反转后,对应的输出为{3,2,1}。
示例一:
输入 {1,2,3};
输出 {3,2,1};
实例:反转链表的实现
import streamlit as st
# 定义链表节点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 定义反转链表函数
def reverseList(head: ListNode) -> ListNode:
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
# 初始化链表
def initList(nums: list) -> ListNode:
dummy_head = ListNode(0)
cur = dummy_head
for num in nums:
node = ListNode(num)
cur.next = node
cur = cur.next
return dummy_head.next
# 输出链表节点值
def printList(head: ListNode):
res = []
cur = head
while cur:
res.append(cur.val)
cur = cur.next
st.write(res)
# Streamlit App
def main():
st.title("使用C语言反转链表")
nums = st.text_input("请输入链表节点值,用英文逗号隔开:")
if nums:
nums = nums.split(",")
nums = [int(num) for num in nums]
head = initList(nums)
st.write("原链表:")
printList(head)
new_head = reverseList(head)
st.write("反转后的链表:")
printList(new_head)
if __name__ == '__main__':
main()
返回结果:
默认链表不为空;若为空,可以使用一个if/else条件就可以实现。
原链表:
[
0:1
1:2
2:3
]
反转后的链表:
[
0:3
1:2
2:1
]