func(l *MyLinkedList) Get(index int) int { if index < 0 || index >= l.size{ return-1 } current := l.head for i:=0;i<=index;i++{ current = current.Next } return current.Val } func(l*MyLinkedList)AddAtHead(val int){ l.AddAtIndex(0,val) } func(l*MyLinkedList)AddAtTail(val int){ l.AddAtIndex(l.size,val) } func(l*MyLinkedList)AddAtIndex(index, val int){ if index > l.size{ return } index =max(index,0) //if index < 0 { // index = 0 //} current :=l.head for i:=0;i<index;i++{ current = current.Next } l.size++ toAdd := &ListNode{val, current.Next} //toAdd.Next=current.Next current.Next=toAdd } func(l*MyLinkedList) DeleteAtIndex(index int){ if index >=l.size || index <0{ return } current :=l.head for i:=0;i<index;i++{ current=current.Next } l.size-- current.Next=current.Next.Next }
funcmax(a, b int)int { if b > a { return b } return a }
funcreverseList(head *ListNode) *ListNode { if head == nil { returnnil } var pre *ListNode current := head for current !=nil { temp := current.Next current.Next=pre pre=current current = temp } return pre
* type ListNode struct { * Val int * Next *ListNode * } */ funcremoveNthFromEnd(head *ListNode, n int) *ListNode { demmyHead := &ListNode{0,head} fast,slow := demmyHead,demmyHead f :=0 for f < n { f++ fast=fast.Next } for fast.Next!=nil { fast=fast.Next slow=slow.Next } slow.Next=slow.Next.Next return demmyHead.Next }
funcdetectCycle(head *ListNode) *ListNode { fast,slow := head ,head for fast != nil && fast.Next!=nil && fast.Next.Next!=nil{ fast = fast.Next.Next slow = slow.Next if fast == slow { fast = head for fast != slow { fast = fast.Next slow = slow.Next } return fast } } returnnil }
funcdetectCycle(head *ListNode) *ListNode { hashMap := map[*ListNode]int{} current := head for current != nil { if _,ok :=hashMap[current]; ok { return current }else { hashMap[current]=1 } current = current.Next } returnnil }