单链表
单链表的基本结构:
class ListNode:
def __init__(self, val, next=None):
self.val = val
self. Next = next
移除链表元素
接下来这题,涉及链表的删除:203. 移除链表元素
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
pre = __head = ListNode(val=0, next=head)
cur = head
while cur != None:
if cur.val == val:
pre.next = cur.next
else:
pre = pre.next
cur = cur.next
return __head. Next
这里,我们使用了头指针__head
来指向链表的头head
,pre
表示cur
的前一个位置指针,这样方便操作。总体而言,代码是需要判断cur
的值是否等于val
。
单链表的增删查改
对于单链表的增删查改,707. 设计链表 这题总结的比较好。
注意点
- 需要设计
ListNode
来表示节点的类。 - 对于一个单链表,都有链表的长度
length
和链表的头指针__head
。 - 对于方法
get
,addAtIndex
,deleteAtIndex
都需要使用条件语句判断输入值是否超出了单链表长度。注意addAtIndex
中index
是可以等于length
的,相当于是在单链表末尾加上一个节点。 - 使用
showLinkedlist
方法可视化了一下。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.__head = ListNode()
self.length = 0
def get(self, index: int) -> int:
if index >= self.length or index < 0: return -1
cur = self.__head
for _ in range(index + 1):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
NewNode = ListNode(val, self.__head.next)
self.__head.next = NewNode
self.length += 1
def addAtTail(self, val: int) -> None:
NewNode = ListNode(val, None)
cur = self.__head
for _ in range(self.length):
cur = cur.next
cur.next = NewNode
self.length += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.length: return
NewNode = ListNode(val)
pre = self.__head
for _ in range(index):
pre = pre.next
NewNode.next = pre.next
pre.next = NewNode
self.length += 1
def deleteAtIndex(self, index: int) -> None:
if index > self.length - 1 or index < 0: return
cur = self.__head
for _ in range(index):
cur = cur.next
cur.next = cur.next.next
self.length -= 1
def showLinkedlist(self):
cur = self.__head.next
linkedlist = []
while cur != None:
linkedlist.append(cur.val)
cur = cur.next
print(linkedlist)
为了代码能够在Pycharm中运行,我们按照题目设计了例子。
# Your MyLinkedList object will be instantiated and called as such:
obj = MyLinkedList()
obj.addAtHead(1)
obj.showLinkedlist() # [1]
obj.addAtTail(3)
obj.showLinkedlist() # [1, 3]
obj.addAtIndex(1, 2)
obj.showLinkedlist() # [1, 2, 3]
param_1 = obj.get(1)
print(param_1) # 2
obj.deleteAtIndex(1)
obj.showLinkedlist() # [1, 3]