#本人解法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if head isNone: returnNone a = [] while head: if head.val != val: a.append(head) head = head.next l = len(a) if l == 0: returnNone for i inrange(l - 1): a[i].next = a[i + 1] a[l - 1].next = None return a[0]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if head isNone: returnNone head.next = self.removeElements(head.next, val) return head.nextif head.val == val else head # 链表的定义具有递归的性质,因此链表题目常可以用递归的方法求解。这道题要求 # 删除链表中所有节点值等于特定值的节点,可以用递归实现。对于给定的链表, # 首先对除了头节点 head 以外的节点进行删除操作,然后判断 head 的节点值 # 是否等于给定的 val。如果 head 的节点值等于 val,则 head 需要被删除, # 因此删除操作后的头节点为 head.next;如果 head 的节点值不等于 val, # 则 head 保留,因此删除操作后的头节点还是 head。上述过程是一个递归的过程。 # 递归的终止条件是 head 为空,此时直接返回 head。当 head 不为空时, # 递归地进行删除操作,然后判断 head 的节点值是否等于 val 并决定是否要删除 head。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 迭代 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: dummy_head = ListNode(0, 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
//本人解法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveElements(head *ListNode, val int) *ListNode { if head == nil { returnnil } var a []*ListNode for head != nil { if head.Val != val { a = append(a, head) } head = head.Next } l := len(a) if l == 0 { returnnil } for i := 0; i < l-1; i++ { a[i].Next = a[i+1] } a[l-1].Next = nil return a[0] }
//递归 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveElements(head *ListNode, val int) *ListNode { if head == nil { return head } head.Next = removeElements(head.Next, val) if head.Val == val { return head.Next } else { return head } }
/* 链表的定义具有递归的性质,因此链表题目常可以用递归的方法求解。这道题要求 删除链表中所有节点值等于特定值的节点,可以用递归实现。对于给定的链表,首先对除了头节点 head 以外的节点进行删除操作,然后判断 head 的节点值是否等于给定的 val。如果 head 的节点值等于 val,则 head 需要被删除,因此删除操作后的头节点为 head.next;如果 head 的节点值不等于 val,则 head 保留,因此删除操作后的头节点还是 head。上述过程是一个递归的过程。递归的终止条件是 head 为空,此时直接返回 head。当 head 不为空时,递归地进行删除操作,然后判断 head 的节点值是否等于 val 并决定是否要删除 head。 */
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//迭代 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveElements(head *ListNode, val int) *ListNode { dummyHead := &ListNode{Next: head} for tmp := dummyHead; tmp.Next != nil; { if tmp.Next.Val == val { tmp.Next = tmp.Next.Next } else { tmp = tmp.Next } } return dummyHead.Next }
defaddAtIndex(self, index: int, val: int) -> None: if index > self.size: return self.size += 1 index = max(0, index) cur = self.head for _ inrange(index): cur = cur.next add = ListNode(val) add.next = cur.next cur.next = add return
defdeleteAtIndex(self, index: int) -> None: if index < 0or index >= self.size: return self.size -= 1 cur = self.head for _ inrange(index): cur = cur.next cur.next = cur.next.next return
# 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)
func(l *MyLinkedList) Get(index int) int { if index < 0 || index >= l.size { return-1 } cur := l.head for i := 0; i <= index; i++ { cur = cur.Next } return cur.Val }
func(l *MyLinkedList) AddAtIndex(index, val int) { if index > l.size { return } index = max(index, 0) l.size++ pred := l.head for i := 0; i < index; i++ { pred = pred.Next } toAdd := &ListNode{val, pred.Next} pred.Next = toAdd }
func(l *MyLinkedList) DeleteAtIndex(index int) { if index < 0 || index >= l.size { return } l.size-- pred := l.head for i := 0; i < index; i++ { pred = pred.Next } pred.Next = pred.Next.Next }
funcmax(a, b int)int { if b > a { return b } return a }
/** * Your MyLinkedList object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Get(index); * obj.AddAtHead(val); * obj.AddAtTail(val); * obj.AddAtIndex(index,val); * obj.DeleteAtIndex(index); */
#本人解法 classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: a = [] if head isNone: returnNone while head: a.append(head) head = head.next for i inrange(len(a) - 1, 0, -1): a[i].next = a[i - 1] a[0].next = None return a[-1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#迭代解法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: pre = None cur = head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
//本人解法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcreverseList(head *ListNode) *ListNode { var a []*ListNode if head == nil { returnnil } for head != nil { a = append(a, head) head = head.Next } for i := len(a) - 1; i > 0; i-- { a[i].Next = a[i-1] } a[0].Next = nil return a[len(a)-1] }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//官方解法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcreverseList(head *ListNode) *ListNode { var prev *ListNode curr := head for curr != nil { next := curr.Next curr.Next = prev prev = curr curr = next } return prev }
# 双指针法(对称) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: dummy = ListNode(0, head) first = head second = dummy for i inrange(n): first = first.next
while first: first = first.next second = second.next second.next = second.next.next return dummy.next
// 双指针法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveNthFromEnd(head *ListNode, n int) *ListNode { dummy := &ListNode{0, head} first, second := head, dummy for i := 0; i < n; i++ { first = first.Next } for ; first != nil; first = first.Next { second = second.Next } second.Next = second.Next.Next return dummy.Next }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//数组 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveNthFromEnd(head *ListNode, n int) *ListNode { nodes := make([]*ListNode, 0) dummy := &ListNode{0, head} for node := dummy; node != nil; node = node.Next { nodes = append(nodes, node) } prev := nodes[len(nodes)-1-n] prev.Next = prev.Next.Next return dummy.Next }
//数组 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveNthFromEnd(head *ListNode, n int) *ListNode { a := make([]*ListNode, 0) for head != nil { a = append(a, head) head = head.Next } a = append(a[:len(a)-n], a[len(a)-n+1:]...) for i := 0; i < len(a)-1; i++ { a[i].Next = a[i+1] } iflen(a) == 0 { returnnil } a[len(a)-1].Next = nil return a[0] }
curr = headB while curr: if curr in hash_map: return curr curr = curr.next
returnNone
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#双指针 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defgetIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: A, B = headA, headB while A != B: A = A.nextif A else headB B = B.nextif B else headA return A
//双指针 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcgetIntersectionNode(headA, headB *ListNode) *ListNode { a, b := headA, headB for a != b { if a != nil { a = a.Next } else { a = headB } if b != nil { b = b.Next } else { b = headA } } return a }
# 内存少 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: num = 10**5 + 1 tmp = head while tmp: if tmp.val == num: returnTrue else: tmp.val = num tmp = tmp.next returnFalse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 哈希表 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: vis = {} tmp = head while tmp: if tmp notin vis.keys(): vis[tmp] = True else: returnTrue tmp = tmp.next returnFalse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 双指针法 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: slow = fast = head # 乌龟和兔子同时从起点出发 while fast and fast.next: slow = slow.next# 乌龟走一步 fast = fast.next.next# 兔子走两步 if fast is slow: # 兔子追上乌龟(套圈),说明有环 returnTrue returnFalse# 访问到了链表末尾,无环 # 兔子会不会「跳过」乌龟,从来不会和乌龟相遇呢? # 这是不可能的。如果有环的话,那么兔子和乌龟都会进入环中。这时用「相对速度」思考,乌龟不动,兔子相对乌龟每次只走一步,这样就可以看出兔子一定会和乌龟相遇了。
// 双指针法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
funchasCycle(head *ListNode)bool { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if fast == slow { returntrue } } returnfalse }
# 本人解法 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: num = 10**5 + 1 tmp = head while tmp: if tmp.val == num: return tmp else: tmp.val = num tmp = tmp.next returnNone
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 哈希表 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: vis = {} tmp = head while tmp: if tmp notin vis.keys(): vis[tmp] = True else: return tmp tmp = tmp.next returnNone
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 双指针法,其实就将这道题变成了数学题 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if fast is slow: while slow isnot head: slow = slow.next head = head.next return slow returnNone
//双指针法 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcdetectCycle(head *ListNode) *ListNode { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if fast == slow { for slow != head { slow = slow.Next head = head.Next } return slow } } returnnil }