leetcode打卡笔记(每天更新......)

1、移除链表元素

func removeElements(head *ListNode, val int) *ListNode {
    p := &ListNode{}
    p.Next = head
	
	pre := p
    cur := head

	for cur != nil {
		if cur.Val == val {
			pre.Next = cur.Next
			cur = cur.Next
		}else {
			pre = cur
			cur = cur.Next
		}
	}
	return p.Next
}

2、设计链表 707

type MyLinkedList struct {
	head *ListNode
	size int
}

func Constructor() MyLinkedList {
	return MyLinkedList{&ListNode{}, 0}
}

func (this *MyLinkedList) Get(index int) int {
	if index < 0 || index >= this.size {
		return -1
	}
	cur := this.head
	for i := 0; i <= index; i++ {
		cur = cur.Next
	}
	return cur.Val
}

func (this *MyLinkedList) AddAtHead(val int) {
	this.AddAtIndex(0, val)
}

func (this *MyLinkedList) AddAtTail(val int) {
	this.AddAtIndex(this.size, val)
}

func (this *MyLinkedList) AddAtIndex(index int, val int) {
	if index > this.size {
		return
	}
	this.size++

	pre := this.head
	for i := 0; i < index; i++ {
		pre = pre.Next
	}

	cur := &ListNode{Val: val, Next: nil}
	cur.Next = pre.Next
	pre.Next = cur
}

func (this *MyLinkedList) DeleteAtIndex(index int) {
	if index < 0 || index >= this.size {
		return
	}
	this.size--
	p := this.head
	for i := 0; i < index; i++ {
		p = p.Next
	}
	p.Next = p.Next.Next
}


/**
 * 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);
 */

3、反转链表

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
//1 2 3 4 5
func reverseList(head *ListNode) *ListNode {
	var pre *ListNode = nil //*
	cur := head
	for cur != nil {
		next := cur.Next //先指向 (位置很关键)
		cur.Next = pre // 反转指针
		pre = cur
		cur = next
	}
	return pre
}

4、两两交换链表中的节点 24

//递归
func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	newHead := head.Next
	head.Next = swapPairs(newHead.Next)
	newHead.Next = head
	return newHead
}
//非递归
func swapPairs(head *ListNode) *ListNode {
	newHead := &ListNode{}
	newHead.Next = head
	temp := newHead
	for temp.Next != nil && temp.Next.Next != nil {
		node1 := temp.Next
		node2 := temp.Next.Next

		temp.Next = node2
		node1.Next = node2.Next
		node2.Next = node1

		temp = node1
	}
	return newHead.Next
}

5、删除链表的倒数第n个节点——19

func removeNthFromEnd(head *ListNode, n int) *ListNode {
	if head == nil {
		return head
	}
	size := 0
	p := head
	for p != nil {
		p = p.Next
		size++
	}
	newHead := &ListNode{0,head}
	cur := newHead
	for i := 0; i < size-n; i++ {
		cur = cur.Next
	}
	if cur.Next.Next != nil {
		cur.Next = cur.Next.Next
	} else {
		cur.Next = nil
	}
	return newHead.Next
}

你可能感兴趣的:(leetcode,笔记,算法,go,后端)