203 移除链表元素
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeElements(head *ListNode, val int) *ListNode {
dummyHead := &ListNode{
Next: head,
}
res := dummyHead
for dummyHead.Next != nil {
if(dummyHead.Next.Val == val){
dummyHead.Next = dummyHead.Next.Next
}else{
dummyHead = dummyHead.Next
}
}
return res.Next
}
707 设计链表
type MyLinkedList struct {
Node *Node
}
type Node struct{
Val int
Next *Node
Prev *Node
}
func Constructor() MyLinkedList {
node := &Node{
Val: -1,
Next: nil,
Prev: nil,
}
node.Next = node
node.Prev = node
return MyLinkedList{node}
}
func (this *MyLinkedList) Get(index int) int {
node := this.Node.Next
for index > 0 && node.Next != this.Node{
index--
node = node.Next
}
if(index != 0){
return -1
}
return node.Val
}
func (this *MyLinkedList) AddAtHead(val int) {
node := &Node{
Val: val,
Next: this.Node.Next,
Prev: this.Node,
}
this.Node.Next.Prev = node
this.Node.Next = node
}
func (this *MyLinkedList) AddAtTail(val int) {
node := &Node{
Val: val,
Next: this.Node,
Prev: this.Node.Prev,
}
this.Node.Prev.Next = node
this.Node.Prev = node
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if(index < 0){
node := &Node{
Val: val,
Next: this.Node.Next,
Prev: this.Node,
}
this.Node.Next.Prev = node
this.Node.Next = node
}
a := this.Node.Next
for index > 0 && a!=this.Node{
a = a.Next
index--
}
if(index == 0){
b := &Node{
Val: val,
Next: a,
Prev: a.Prev,
}
a.Prev.Next = b
a.Prev = b
}
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
if(index < 0){
return
}
a := this.Node.Next
for index > 0 && a.Next != this.Node{
a = a.Next
index--
}
if(index == 0){
a.Prev.Next = a.Next
a.Next.Prev = a.Prev
}
}
206 反转链表
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var cur,prev *ListNode
cur = head
for cur != nil{
tmp := cur.Next
cur.Next = prev
prev = cur
cur = tmp
}
return prev
}
简要总结 :
203的题比较简单,设置了一个虚结点就好做了,707的题思路比较快,但一直没有完全通过,其中的边界问题需要仔细考虑,尤其是Get、AddAt、Delete这三个部分的边界,而且题意说的是索引。206比较基础,没啥好说的。