LeetCode Practice Journal | Day3_链表(go)

LeetCode Practice Journal | Day3_链表(go)

链表定义

type ListNode struct {
    Val int
    Next *ListNode
}
//创建一个空结点
dummyHead := &ListNode{}

6、leetcode203 移除链表元素

引用文本
1.题目链接:https://leetcode.cn/problems/remove-linked-list-elements/
注意有没有头节点,要不要头节点

代码

// go 没有头节点,再原本链表上操作
func removeElements(head *ListNode, val int) *ListNode {
    if head==nil{
        return head
    }
    cur := head
    for cur.Next!=nil{
        if cur.Next.Val==val{
            cur.Next = cur.Next.Next
        }else{
            cur = cur.Next
        }
    }
    if head.Val ==val{
        head = head.Next
    }
    return head
}
//创建一个头结点去操作
func removeElements(head *ListNode, val int) *ListNode {
    dummyhead := &ListNode{}
    dummyhead.Next=head
    cur := dummyhead
    for cur.Next!=nil{
        if cur.Next.Val==val{
            cur.Next = cur.Next.Next
        }else{
            cur = cur.Next
        }

    }
    return dummyhead.Next
}

7、leetcode707 设计链表

引用文本
1.题目链接:https://leetcode.cn/problems/design-linked-list/
注意链表初始化,新结点初始化

单链表

// 
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
    }
    index = max(index,0)
    this.size++
    pred := this.head
    for i:=0;i<index;i++{
        pred = pred.Next
    }
    toAdd := &ListNode{val,pred.Next}
    pred.Next= toAdd
}


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

func max(a,b int) int{
    if b>a{
        return b
    }else{
        return a
    }
}

8 leetcode206 反转链表

引用文本
1.题目链接:https://leetcode.cn/problems/reverse-linked-list/

迭代和递归

//迭代
func reverseList(head *ListNode) *ListNode {
    cur:= head
    pre := &ListNode{}
    pre = nil
    for cur!=nil{
        next := cur.Next
        cur.Next = pre
        pre = cur
        cur = next
    }
    return pre
}
//递归
func reverseList(head *ListNode) *ListNode {
    if head==nil||head.Next==nil{
        return head
    }
    newhead:= reverseList(head.Next)
    head.Next.Next=head
    head.Next = nil
    return newhead
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值