微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
}

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐