刷题笔记day03-链表
前言
今天是刷题的第三天,坚持就是胜利
203.移除链表元素
增加一个头结点,这样可以统一删除操作
另外,遇到等于的值,就让 prev 指向 curr.Next ,同时将curr更新指向 prev.Next。
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeElements(head *ListNode, val int) *ListNode {
// 思路:增加一个头结点,并且设置一个prev指针,用于删除
newHead := &ListNode{}
newHead.Next = head
prev := newHead
curr := newHead
for curr != nil {
if curr.Val == val {
prev.Next = curr.Next
curr = prev.Next
} else {
prev = curr
curr = curr.Next
}
}
return newHead.Next
}
707. 设计链表
测试代码,
type Node struct {
Val int
Next *Node
}
type MyLinkedList struct {
Size int
Head *Node
}
func Constructor() MyLinkedList {
// 带有虚拟头节点
head := &Node{
Val: -1,
Next: nil,
}
return MyLinkedList{0, head}
}
func (this *MyLinkedList) Get(index int) int {
// 判断非法性
if (index < 0 || index > (this.Size - 1)) {
return -1
}
node := this.Head
for i := 0; i <= index; i++ {
if node == nil {
return -1
} else {
node = node.Next
}
}
return node.Val
}
func (this *MyLinkedList) AddAtHead(val int) {
node := &Node {
Val: val,
Next: nil,
}
node.Next = this.Head.Next
this.Head.Next = node
this.Size++
}
func (this *MyLinkedList) AddAtTail(val int) {
node := this.Head
// node指向最后一位非nil
for node.Next != nil {
node = node.Next
}
node.Next = &Node{
Val: val,
Next: nil,
}
this.Size++
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index > this.Size {
return
}else if index == this.Size { //直接添加到末尾
this.AddAtTail(val)
return
}else if index < 0 {
index = 0
}
// header 指向插入位置的前一位
header := this.Head
for i := 0; i <= index - 1; i++ {
header = header.Next
}
node := &Node{val, nil}
node.Next = header.Next
header.Next = node
this.Size++
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
// 判断是否有效
if index >= this.Size || index < 0 {
return
}
// header 指向插入位置的前一位
header := this.Head
for i := 0; i <= index - 1; i++ {
header = header.Next
}
header.Next = header.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);
*/
206. 反转链表
// 使用双指针,pre指向前一个,curr指向当前的,前后调转方向既可。
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
// 使用双指针
var prev *ListNode
curr := head
var tmp *ListNode
for curr != nil {
tmp = curr.Next
curr.Next = prev
prev = curr
// curr往后移动一位
curr = tmp
}
return prev
}