203. 移除链表元素
- 头节点前➕哑节点是常规操作了
- 说实话在题解里看到递归的那一刻我是懵的
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy = ListNode(0, head)
pre = dummy
cur = head
while(cur):
if cur.val == val:
pre.next = cur.next
else:
pre = pre.next
cur = cur.next
return dummy.next
707. 设计链表
- 主要思路还是在于记录哑节点,来方便后续的增加和删除节点操作
class ListNode():
def __init__(self, val, next=None):
self.val = val
self.next = next
class MyLinkedList(object):
def __init__(self):
self.dummy = ListNode(0)
self.size = 0
def get(self, index):
"""
:type index: int
:rtype: int
"""
if index < 0 or index >=self.size:
return -1
cur = self.dummy.next
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
self.dummy.next = ListNode(val, self.dummy.next)
self.size += 1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
self.addAtIndex(self.size, val)
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index > self.size or index < 0:
return
pre = self.dummy
for i in range(index):
pre = pre.next
pre.next = ListNode(val, pre.next)
self.size += 1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index < 0 or index >=self.size:
return
pre = self.dummy
for i in range(index):
pre = pre.next
pre.next = pre.next.next
self.size -= 1
206. 反转链表
- 一次面试的时候被问过,应该是想放水让我过的吧,但是我没做出来啊阿啊阿
- 但这个递归法,还是,有点离谱了。甚至加大了空间复杂度,O(n)
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
curr = head
pre = None
while(curr):
tmp = curr.next
curr.next = pre
pre = curr
curr = tmp
return pre
return self.reverse(head, None)
def reverse(self, cur, pre):
if cur = None:
return pre
tmp = cur.next
cur.next = pre
return self.reverse(temp, cur)