203. 移除链表元素 - 力扣(LeetCode)
之前没接触过链表,直接看讲解
解题思路
有两种,单独处理头节点,或者设置虚拟头节点,让头节点作为普通节点
方法一 使用原链表
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
while head :
if head.val == val:
head = head.next
else:
break
current = head
while current and current.next is not None:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return head
方法二 虚拟头节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode()
dummy_head.next = head
current = dummy_head
while current.next:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return dummy_head.next
707. 设计链表 - 力扣(LeetCode)
单链表
class ListNode():
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList(object):
def __init__(self):
self.dummy_head = ListNode()
self.size = 0
def get(self, index):
"""
:type index: int
:rtype: int
"""
if index < 0 or index >= self.size:
return -1
current = self.dummy_head.next
for i in range(index):
current = current.next
return current.val
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
self.dummy_head.next = ListNode(val, self.dummy_head.next)
self.size += 1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
current = self.dummy_head
while current.next:
current = current.next
current.next = ListNode(val)
self.size += 1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index < 0 or index > self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = ListNode(val, current.next)
self.size += 1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index < 0 or index >= self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = current.next.next
self.size -= 1
- 下标是从dummy_head.next开始,从0开始
- 参考代码随想录 (programmercarl.com)
206. 反转链表 - 力扣(LeetCode)
双指针法
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
pre = None
while cur:
temp = cur.next #保存cur下一个节点
cur.next = pre # 反转
pre = cur #面向对象
cur = temp
return pre
递归
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.reverseNode(head, None)
def reverseNode(self, cur, pre):
if cur is None:
return pre
temp = cur.next
cur.next = pre
return self.reverseNode(temp, cur)
- 注意类的写法
- 递归还需练习