/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveElements(head *ListNode, val int) *ListNode { for head!= nil && head.Val == val{ head = head.Next } if head == nil{ return head } //复习new结构体 dummy := &ListNode{ Val : -1, Next : head, } pre := dummy cur := head for cur != nil{ if cur.Val == val{ pre.Next = cur.Next }else{ pre = cur } cur = cur.Next } return head
}
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcremoveElements(head *ListNode, val int) *ListNode { dummy := &ListNode{} dummy.Next = head cur := dummy//这里 赋值为dummy 而不是dummy.Next(指多了) for cur != nil && cur.Next!= nil{ if cur.Next.Val == val{ cur.Next = cur.Next.Next }else{ cur = cur.Next } } return dummy.Next
/** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */
func(this *MyLinkedList) AddAtIndex(index int, val int) { if index > this.Size { return } if index < 0{ index =0 } dummy := this.Head for i:=0 ;i < index;i++{ dummy = dummy.Next } NewNode := &Node{ Val:val, Next: dummy.Next, } dummy.Next = NewNode this.Size++ }
func(this *MyLinkedList) DeleteAtIndex(index int) { if index <0|| index >= this.Size{ //大于等于size直接无效 return } dummy := this.Head for i :=0;i< index;i++{ dummy = dummy.Next } dummy.Next = dummy.Next.Next this.Size--
}
/** * 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); */
length++; } publicvoiddeleteAtIndex(int index) { if(index >= length || index <0 )return ; ListNodedummy=newListNode(-1,head); ListNodepre= dummy.next; for(inti=0; i < index;i++){ pre = pre.next; } pre.next.next.prev = pre; pre.next = pre.next.next;
length--; } }
/** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funcreverseList(head *ListNode) *ListNode { if head == nil{ return head } cur := head var pre *ListNode for cur != nil{ node:= cur.Next cur.Next = pre pre = cur cur = node } //届时的head只指向最后的1 return pre }