赞
踩
链表在内存中不是连续分布的
头节点与非头节点移除方法不一样
运用虚拟头节点来简化代码
# 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( next = head) cur = dummy_head while cur.next: if cur.next.val == val: cur.next = cur.next.next else: cur = cur.next return dummy_head.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 cur = self.dummy_head.next for i in range(index): cur = cur.next return cur.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 """ cur = self.dummy_head while cur.next: cur = cur.next cur.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 cur = self.dummy_head for i in range(index): cur = cur.next cur.next = ListNode(val, cur.next) self.size +=1 def deleteAtIndex(self, index): """ :type index: int :rtype: None """ cur = self.dummy_head if index < 0 or index > self.size: return for i in range (index): cur = cur.next cur.next = cur.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)
# 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 reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head pre = None while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
链表不是很会,明天再复习一下基础知识
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。