go实现处理链表的算法
链表的算法分为几种类型
1,删除链表的倒数第N个节点
2,合并两个有序链表
3,判断链表是否是环形链表
4,两个链表的位数相加
package main
import "fmt"
type ListNode struct {
data int
next *ListNode
}
//删除链表倒数第N个节点
func deleteListNode(head *ListNode,n int) *ListNode {
result := &ListNode{}
result.next = head
var pre *ListNode
cur := result
i :=1
for head != nil{
if i >=n{
pre = cur
cur = cur.next
}
head = head.next
i++
}
pre.next = pre.next.next
return result.next
}
//合并两个有序链表
func sumTwoListNode(l1 *ListNode,l2 *ListNode) *ListNode {
preHead := &ListNode{}
result := preHead
for l1 !=nil && l2 != nil{
if l1.data<l2.data{
preHead.next = l1
l1 = l1.next
}else{
preHead.next = l2
l2 = l2.next
}
preHead = preHead.next
}
if l1 !=nil{
preHead.next = l1
}
if l2 != nil{
preHead.next = l2
}
return result.next
}
//方式1 ,使用map
func isCycle(head *ListNode) bool{
m1 := make(map[*ListNode]int)
for head != nil{
if _,ok := m1[head];ok{
return true
}
m1[head] = 1
head = head.next
}
return false
}
func isCycleTwo(head *ListNode) bool {
if head == nil{
return false
}
fast := head.next //走两步的初始指针
for head !=nil && fast !=nil && fast.next !=nil{
if head == fast{
return true
}
fast = fast.next.next
head = head.next
}
return false
}
//给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
func sumTwolist(l1 *ListNode,l2 *ListNode) *ListNode {
list := &ListNode{0,nil}
result :=list
tmp :=0
for l1 !=nil || l2 !=nil || tmp !=0{
if l1 !=nil{
tmp +=l1.data
l1 = l1.next
}
if l2 !=nil{
tmp +=l2.data
l2 = l2.next
}
list.next = &ListNode{tmp%10,nil}
tmp = tmp/10
list = list.next
}
return result.next
}
func main() {
list := []int{1,2,3}
head := &ListNode{data:list[0]}
tail := head
for i:=1;i<len(list);i++{
tail.next = &ListNode{data: list[i]}
tail = tail.next
}
//************删除测试
//newList := deleteListNode(head,2)
//newList.show()
list2 := []int{4,5,6}
head2 := &ListNode{data:list2[0]}
tail2 := head2
for i :=1;i<len(list2);i++{
tail2.next = &ListNode{data: list2[i]}
tail2 = tail2.next
}
//合并两个链表测试
//newlist2 := sumTwoListNode(head,head2)
//newlist2.show()
//测试两个链表相加
newlist3 := sumTwolist(head,head2)
newlist3.show()
}
//打印链表
func (l *ListNode) show() {
fmt.Println(l.data)
for l.next != nil{
l = l.next
fmt.Println(l.data)
}
}
翻转链表
func reverseListNode(head *ListNode) *ListNode {
var node *ListNode
for head !=nil{
//head.next,node,head = node,head,head.next
tmp := head.next
head.next = node
node = head
head = tmp
}
return node
}

浙公网安备 33010602011771号