203.移除链表元素
普通的链表节点删除方式:(伪代码)
好处:直接易于理解;坏处:需要分为头节点和非头节点单独操作
while(head!=NULL && head->val == target): //先删头节点
head = head->next;
curr = head; //建立一个虚拟节点
// 由于单链表是单向的,所以以curr为基准,检查curr->next
while(curr != Null && curr->next != Null):
if (curr->next->val == target):
curr->next = cur->next->next
else:
curr = curr->next
return head //最后返回的是头节点,不是虚拟的curr
虚拟头节点的删除方式:(伪代码)
好处:不用对头节点单独操作;需要注意返回值
dummyhead = new Listnode() // 创建一个新的节点
dummyhead->next = head //让下一个指向头节点
curr = dummyhead //还是需要一个虚拟节点来进行操作
操作过程同上
return dummyhead->next
正式代码python:
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummyhead = ListNode()
dummyhead.next = head
curr = dummyhead
while curr.next != None:
if curr.next.val == val:
curr.next = curr.next.next
else:
curr = curr.next
return dummyhead.next
707.设计链表(运用了链表的所有操作)
注意边界条件!!
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummyhead = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index<0 or index>=self.size:
return -1
curr = self.dummyhead.next
for i in range(index):
curr = curr.next
return curr.val
def addAtHead(self, val: int) -> None:
curr = ListNode(val, self.dummyhead.next)
self.dummyhead.next = curr
self.size +=1
def addAtTail(self, val: int) -> None:
curr = self.dummyhead
while curr.next != None:
curr = curr.next
curr.next = ListNode(val)
self.size +=1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
curr = self.dummyhead
for i in range(index):
curr = curr.next
new_node = ListNode(val, curr.next)
curr.next = new_node
self.size +=1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
curr = self.dummyhead
for i in range(index):
curr = curr.next
curr.next = curr.next.next
self.size -=1
# 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.反转链表
这道题就是想的时候要多想想,用了两个指针相当于,同时最后向前前进的时候是先更新谁容易犯错
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return head
pre = None
curr = head
while curr!= None:
temp1 = curr.next
curr.next = pre
pre = curr
curr = temp1
return pre