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
}