LC707 - Go 设计链表

LeetCode - 707.设计链表

题目链接

707.设计链表

代码

package main

// 虚拟节点
type MyLinkedList struct {
    
    
	dummy *Node
}

type Node struct {
    
    
	val int
	next *Node
}

func Constructor() MyLinkedList {
    
    
	rear := &Node{
    
    
		val:  -1,
		next: nil,
	}

	return MyLinkedList{
    
    rear}
}

func (this *MyLinkedList) Get(index int) int {
    
    
	if index < 0 {
    
    
		return -1
	}

	cur := this.dummy.next

	for ;cur != nil; {
    
    
		if index == 0 {
    
    
			return cur.val
		}
		index --
		cur = cur.next
	}

	return -1
}

func (this *MyLinkedList) AddAtHead(val int) {
    
    
	pre := this.dummy
	nextNode := pre.next
	pre.next = &Node{
    
    
		val:  val,
		next: nextNode,
	}
}

func (this *MyLinkedList) AddAtTail(val int) {
    
    
	pre := this.dummy
	for ;pre.next != nil; {
    
    
		pre = pre.next
	}
	pre.next = &Node{
    
    
		val:  val,
		next: nil,
	}
}

func (this *MyLinkedList) AddAtIndex(index int, val int)  {
    
    
	// index判断
	if index < 0 {
    
    
		this.AddAtHead(val)
		return
	}

	pre := this.dummy
	cur := this.dummy.next
	for ;cur != nil; {
    
    
		if index == 0 {
    
    
			break
		}
		pre = pre.next
		cur = cur.next
		index --
	}

	// 如果是0就说明找到了
	if index == 0 {
    
    
		pre.next = &Node{
    
    
			val: val,
			next: cur,
		}
	} else if index == 1 {
    
    
		// 如果是1说明要将结点添加到链表尾部
		this.AddAtTail(val)
		return
	}
	// 如果index > 1说明index越界了 啥都不做
}

func (this *MyLinkedList) DeleteAtIndex(index int)  {
    
    
	pre := this.dummy
	cur := pre.next

	for ;cur != nil; {
    
    
		if index == 0 {
    
    
			pre.next = cur.next
			return
		}
		pre = pre.next
		cur = cur.next
		index --
	}
}

猜你喜欢

转载自blog.csdn.net/qq_44336650/article/details/120895582
今日推荐