203.移除链表元素
虚拟头结点:增加删除都很容易
python不用new,直接=ListNode(...)
# 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]:
# create dummyhead
dummyhead = ListNode(next=head)
cur = dummyhead
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummyhead.next
707.设计链表
增加,删除现有指针要走到index前一个结点。先连后面的↗,再连前面的↘
搞清楚index指哪一个数,[0,....] [1,....],以及指针需要停在哪里
class ListNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
# create an empty list
# self.head = None
# create dummy head
self.dummy_head = ListNode()
self.dummy_head.next = None # self.head
def get(self, index: int) -> int:
cnt = -1
cur = self.dummy_head
while cur.next:
cnt += 1
if cnt == index:
return cur.next.val
else:
cur = cur.next
else:
return -1
def addAtHead(self, val: int) -> None:
new_node = ListNode(val=val, next=self.dummy_head.next)
self.dummy_head.next = new_node
# self.head = new_node # update the head
def addAtTail(self, val: int) -> None:
cur = self.dummy_head
while cur.next:
cur = cur.next
else:
new_node = ListNode(val=val, next=None)
cur.next = new_node
def addAtIndex(self, index: int, val: int) -> None:
cnt = -1
cur = self.dummy_head
while cur.next:
cnt += 1
if cnt == index:
new_node = ListNode(val=val,next=cur.next)
cur.next = new_node
else:
cur = cur.next
else:
if index == cnt+1:
new_node = ListNode(val=val, next=None)
cur.next = new_node
def deleteAtIndex(self, index: int) -> None:
cnt = -1
cur = self.dummy_head
while cur.next:
cnt += 1
if cnt == index:
cur.next = cur.next.next
else:
cur = cur.next
206.反转链表
while cur!=None:
①暂存下一个结点的地址;
②翻转箭头;
③指针向前移一格
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
while cur:
# save the next address
temp = cur.next
# turn the direction
cur.next = pre
# move to the next node
pre = cur
cur = temp
return pre