203. 移除链表元素:
代码思路
设置好pre前置节点,和cur现在节点这些变量,就好搞。
但是要注意,空节点是None,而None是没有next和val这些方法的。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
if head:
pre = None
cur = head
while cur != None:
if cur.val == val:
if pre != None:
pre.next = cur.next
cur = cur.next
elif head != None:
head = head.next
cur = head
continue
elif head == None:
return None
else:
pre = cur
cur = cur.next
return head
else:
return None
707. 设计链表
代码思路
该题是先构建节点的类,再在链表的类中调用节点类。
class Node:
def __init__(self):
self.val = None
self.next = None
class MyLinkedList:
def __init__(self):
self.head = None
def get(self, index: int) -> int:
cur = self.head
for i in range(index + 1):
if i == index:
if cur == None:
return -1
return cur.val
elif cur.next == None:
return -1
else:
cur = cur.next
def addAtHead(self, val: int) -> None:
add_node = Node()
add_node.val = val
add_node.next = self.head
self.head = add_node
def addAtTail(self, val: int) -> None:
cur = self.head
tail = Node()
tail.val = val
while cur:
if cur.next == None:
cur.next = tail
return None
else:
cur = cur.next
self.head = tail
def addAtIndex(self, index: int, val: int) -> None:
insert_node = Node()
insert_node.val = val
cur = self.head
if index == 0:
insert_node.next = self.head
self.head = insert_node
return None
n = 1
if self.head:
while n < index:
if cur == None:
break
else:
cur = cur.next
n += 1
if cur != None:
insert_node.next = cur.next
cur.next = insert_node
elif index == 0:
self.head = insert_node
def deleteAtIndex(self, index: int) -> None:
pre = None
cur = self.head
if cur:
if index == 0:
self.head = self.head.next
return None
n = 0
while n < index:
if cur.next == None:
return None
else:
pre = cur
cur = cur.next
n += 1
pre.next = cur.next
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
206. 反转链表
代码思路
同样是设置好pre,和cur这些变量,就好搞。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
if cur:
next = cur.next
while next != None:
next = cur.next
if next == None:
cur.next = pre
break
cur.next = pre
pre = cur
cur = next
return cur