go中单链表

package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}
type List struct {
	headNode *ListNode //头节点
}

func main() {

	//res := letcode.Divide(434,423)
	//fmt.Println(res)

	headNode := &ListNode{}

	listData := headNode
	Insert(1,listData,headNode)
	Insert(2,headNode)
	Insert(4,headNode)

	res := Find(2,listData)
	fmt.Println(res)

	//listData2 := headNode
	//
	//Insert(4,listData2,headNode)
	//Insert(3,headNode)
	//Insert(2,headNode)

	//PrintList(listData)

	//res := MergeTwoLists(listData,listData2)
	//fmt.Println(res)
}

//删除节点
func Delete(value int,list *ListNode) {
	pPrev := FindPrevious(value,list)
	_ = pPrev
	p := Find(value,list)
	pPrev = p.Next
	p = nil
}

// FindPrevious ...
func FindPrevious(value int,list *ListNode) *ListNode {
	p := list
	for p.Next != nil && p.Next.Val != value {
		p = p.Next
	}
	return p
}

// 找出链表里面的(不安全)
func Find(value int,list *ListNode) *ListNode {

	p := list
	for p.Val != value {
		p = p.Next
	}
	return p

}

// 测试是否为最后节点 ...
func IsLast(list *ListNode) bool {
	return list.Next == nil
}

// 测试链表是否为空 ...
func isEmpty(list *ListNode) bool {
	return list == nil
}

// 打印链表 ...
func PrintList(list *ListNode) {

	if list.Next != nil {
		fmt.Println(list.Val)
		PrintList(list.Next)
	} else {
		fmt.Println(list.Val)
	}
}

// 合并两个有序的单链表 ...
func MergeTwoLists(l1 *ListNode,l2 *ListNode) *ListNode {
	if l1 == nil {
		return l2
	}
	if l2 == nil {
		return l1
	}
	var res *ListNode
	if l1.Val >= l2.Val {
		res = l2
		res.Next = MergeTwoLists(l1,l2.Next)
	} else {
		res = l1
		res.Next = MergeTwoLists(l1.Next,l2)
	}
	return res
}

// 插入节点 头插法
func Insert(value int,list *ListNode,position *ListNode) {
	tempCell := new(ListNode)
	//fmt.Println("++++",tempCell)
	if tempCell == nil {
		fmt.Println("out of space!")
	}
	tempCell.Val = value
	tempCell.Next = position.Next
	position.Next = tempCell
}

  

相关文章

背景:计算机内部用补码表示二进制数。符号位1表示负数,0表...
大家好,我们现在来讲解关于加密方面的知识,说到加密我认为不...
相信大家在大学的《算法与数据结构》里面都学过快速排序(Qui...
加密在编程中的应用的是非常广泛的,尤其是在各种网络协议之...
前言我的目标是写一个非常详细的关于diff的干货,所以本文有...
对称加密算法 所有的对称加密都有一个共同的特点:加密和...